Using a custom MSSQL query in spring

I'm trying to run a custom query in spring with an MSSQL DB:

I'm trying to run a custom query in spring with an MSSQL DB:

@Query(value = "SELECT my_id, date, name " +
    "FROM my_events " +
    "WHERE name == :name " +
    "AND date between :starttime and :endtime " +
    "ORDER BY date DESC",
    nativeQuery = true)
List<myDAO> findByNameAndDateBetweenOrderByDateDesc (
    @Param("name")String name,
    @Param("starttime")String starttime,
    @Param("endtime")String endtime
);

When running the application without the custom query I'm getting:

Name for parameter binding must not be null or empty! On JDKs < 8, you need to use @Param for named parameters, on JDK 8 or better, be sure to compile with -parameters.; nested exception is java.lang.IllegalArgumentException: Name for parameter binding must not be null or empty! On JDKs < 8, you need to use @Param for named parameters, on JDK 8 or better, be sure to compile with -parameters.

When running the application without the @Query annotation (using the CrudRepository) it works fine.

The query will be changed to a more complicated query once I figure out the simplified one above, this is why I can't use the CrudRepository function.

Build an OAuth 2.0 Authorization Server With Spring Boot and Spring Security

Build an OAuth 2.0 Authorization Server With Spring Boot and Spring Security

Learn more about building an OAuth 2.0 authorization server with Spring Boot and Spring Security.

Originally published by  Andrew Hughes  he at dzone.com

User management is required for most web applications, but building it isn't always an easy task. Many developers work around the clock to ensure their app is secure by seeking out individual vulnerabilities to patch. Luckily, you can increase your own efficiency by implementing OAuth 2.0 to your web application with Spring Security and Spring Boot. The process gets even easier by integrating with Oktaon top of Spring Boot.

In this tutorial, you’ll first build an OAuth 2.0 web application and authentication server using Spring Boot and Spring Security. After that, you’ll use Okta to get rid of your self-hosted authentication server and simplify your Spring Boot application even more.

Let’s get started!

Create an OAuth 2.0 Server

Start by going to the Spring Initializr and creating a new project with the following settings:

  • Change project type from Maven to Gradle.
  • Change the Group to com.okta.spring.
  • Change the Artifact to AuthorizationServerApplication.
  • Add one dependency: Web.

Download the project and copy it somewhere that makes sense on your hard drive. In this tutorial, you’re going to create three different projects, so you might want to create a parent directory, something like SpringBootOAuthsomewhere.

You need to add one dependency to the build.gradle file:

implementation 'org.springframework.security.oauth:spring-security-oauth2:2.3.3.RELEASE'

This adds in Spring’s OAuth goodness.

Update the src/main/resources/application.properties to match:

server.port=8081
server.servlet.context-path=/auth
user.oauth.clientId=R2dpxQ3vPrtfgF72
user.oauth.clientSecret=fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9
user.oauth.redirectUris=http://localhost:8082/login/oauth2/code/
user.oauth.user.username=Andrew
user.oauth.user.password=abcd

This sets the server port, servlet context path, and some default values for the in-memory, ad hoc generated tokens the server is going to return to the client, as well as for our user’s username and password. In production, you would need to have a bit more of a sophisticated back-end for a real authentication server without the hard-coded redirect URIs and usernames and passwords.

Update the AuthorizationServerApplication class to add @EnableResourceServer:

package com.okta.spring.AuthorizationServerApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@SpringBootApplication
@EnableResourceServer
public class AuthorizationServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthorizationServerApplication.class, args);
    }
}

Create a new class AuthServerConfig in the same package as your application class com.okta.spring.AuthorizationServerApplication under src/main/java (from now on please create Java classes in src/main/java/com/okta/spring/AuthorizationServerApplication). This Spring configuration class enables and configures an OAuth authorization server.

package com.okta.spring.AuthorizationServerApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    @Value("${user.oauth.clientId}")
    private String ClientID;
    @Value("${user.oauth.clientSecret}")
    private String ClientSecret;
    @Value("${user.oauth.redirectUris}")
    private String RedirectURLs;
   private final PasswordEncoder passwordEncoder;
    public AuthServerConfig(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @Override
    public void configure(
        AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
            .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient(ClientID)
            .secret(passwordEncoder.encode(ClientSecret))
            .authorizedGrantTypes("authorization_code")
            .scopes("user_info")
            .autoApprove(true)
            .redirectUris(RedirectURLs);
    }
}

The AuthServerConfig class is the class that will create and return our JSON web tokens when the client properly authenticates.

Create a SecurityConfiguration class:

package com.okta.spring.AuthorizationServerApplication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Value("${user.oauth.user.username}")
    private String username;
    @Value("${user.oauth.user.password}")
    private String password;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
            .antMatchers("/login", "/oauth/authorize")
            .and()
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin().permitAll();
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser(username)
            .password(passwordEncoder().encode(password))
            .roles("USER");
    }
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

The SecurityConfiguration class is the class that actually authenticates requests to your authorization server. Notice near the top where it’s pulling in the username and password from the application.properties file.

Lastly, create a Java class called UserController:

package com.okta.spring.AuthorizationServerApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
@RestController
public class UserController {
    @GetMapping("/user/me")
    public Principal user(Principal principal) {
        return principal;
    }
}

This file allows the client apps to find out more about the users that authenticate with the server.

That’s your authorization server! Not too bad. Spring Boot makes it pretty easy. Four files and a few properties. In a little bit, you’ll make it even simpler with Okta, but for the moment, move on to creating a client app you can use to test the auth server.

Start the authorization server:

./gradlew bootRun

Wait a bit for it to finish running. The terminal should end with something like this:

...
2019-02-23 19:06:49.122  INFO 54333 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path '/auth  '
2019-02-23 19:06:49.128  INFO 54333 --- [           main] c.o.s.A.AuthorizationServerApplication   : Started AuthorizationServerApplication in 3.502 seconds (JVM running for 3.945)

NOTE: If you get an error about JAXB (java.lang.ClassNotFoundException: javax.xml.bind.JAXBException), it’s because you’re using Java 11. To fix this, add JAXB to your build.gradle.

implementation 'org.glassfish.jaxb:jaxb-runtime'
Build Your Client App

Back to Spring Initializr. Create a new project with the following settings:

  • Project type should be Gradle (not Maven).
  • Group: com.okta.spring.
  • Artifact: SpringBootOAuthClient.
  • Add three dependencies: WebThymeleafOAuth2 Client.

Download the project, copy it to its final resting place, and unpack it.

This time you need to add the following dependency to your build.gradle file:

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'

Rename the src/main/resources/application.properties to application.yml and update it to match the YAML below:

server:
port: 8082
session:
cookie:
name: UISESSION
spring:
thymeleaf:
cache: false
security:
oauth2:
client:
registration:
custom-client:
client-id: R2dpxQ3vPrtfgF72
client-secret: fDw7Mpkk5czHNuSRtmhGmAGL42CaxQB9
client-name: Auth Server
scope: user_info
provider: custom-provider
redirect-uri-template: http://localhost:8082/login/oauth2/code/
client-authentication-method: basic
authorization-grant-type: authorization_code
provider:
custom-provider:
token-uri: http://localhost:8081/auth/oauth/token
authorization-uri: http://localhost:8081/auth/oauth/authorize
user-info-uri: http://localhost:8081/auth/user/me
user-name-attribute: name

Notice that here, you’re configuring the clientId and clientSecret, as well as various URIs for your authentication server. These need to match the values in the other project.

Update the SpringBootOAuthClientApplication class to match:

package com.okta.spring.SpringBootOAuthClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootOAuthClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOAuthClientApplication.class, args);
}
}

Create a new Java class called WebController:

package com.okta.spring.SpringBootOAuthClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.Principal;
@Controller
public class WebController {
@RequestMapping("/securedPage")
public String securedPage(Model model, Principal principal) {
return "securedPage";
}
@RequestMapping("/")
public String index(Model model, Principal principal) {
return "index";
}
}

This is the controller that maps incoming requests to your Thymeleaf template files (which you’ll make in a sec).

Create another Java class named SecurityConfiguration:

package com.okta.spring.SpringBootOAuthClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/").authorizeRequests()
.antMatchers("/", "/login
").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}

This class defines the Spring Security configuration for your application: allowing all requests on the home path and requiring authentication for all other routes. It also sets up the Spring Boot OAuth login flow.

The last files you need to add are the two Thymeleaf template files. A full look at Thymeleaf templating is well beyond the scope of this tutorial, but you can take a look at their website for more info.

The templates go in the src/main/resources/templates directory. You’ll notice in the controller above that they’re simply returning strings for the routes. When the Thymeleaf dependencies are included the build, Spring Boot automatically assumes you’re returning the name of the template file from the controllers, and so, the app will look in src/main/resources/templates for a file name with the returned string plus .html.

Create the home template: src/main/resources/templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a>
</body>
</html>

And the secured template: src/main/resources/templates/securedPage.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Secured Page</title>
</head>
<body>
<h1>Secured Page</h1>
<span th:text="${#authentication.name}"></span>
</body>
</html>

I’ll just point out this one line:

<span th:text="${#authentication.name}"></span>

This is the line that will insert the name of the authenticated user. This line is why you needed the org.thymeleaf.extras:thymeleaf-extras-springsecurity5 dependency in the build.gradle file.

Start the client application:

./gradlew bootRun

Wait a moment for it to finish. The terminal should end with something like this:

...
2019-02-23 19:29:04.448 INFO 54893 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''
2019-02-23 19:29:04.453 INFO 54893 --- [ main] c.o.s.S.SpringBootOAuthClientApplication : Started SpringBootOAuthClientApplication in 3.911 seconds (JVM running for 4.403)

Test the Resource Server

Navigate in your browser of choice to your client app at http://localhost:8082/.

Click the Login link.

You’ll be directed to the login page:

Enter username Andrew and password abcd (from the application.properties file from the authentication server).

Click Sign In and you’ll be taken to the super fancy securedPage.html template that should say “Secured Page” and “Andrew”.

Great! It works. Now you’re gonna make it even simpler.

You can stop both server and client Spring Boot apps.

Create an OpenID Connect Application

Okta is a SaaS (software-as-service) authentication and authorization provider. We provide free accounts to developers so they can develop OIDC apps with no fuss. Head over to developer.okta.com and sign upfor an account. After you’ve verified your email, log in and perform the following steps:

  • Go to Application > Add Application.
  • Select application type Web and click Next.
  • Give the app a name. I named mine “Spring Boot OAuth”.
  • Under Login redirect URIs change the value to http://localhost:8080/login/oauth2/code/okta. The rest of the default values will work.
  • Click Done.

Leave the page open of take note of the Client ID and Client Secret. You’ll need them in a moment.

Create a New Spring Boot App

Back to the Spring Initializr one more time. Create a new project with the following settings:

  • Change project type from Maven to Gradle.
  • Change the Group to com.okta.spring.
  • Change the Artifact to OktaOAuthClient.
  • Add three dependencies: WebThymeleafOkta.
  • Click Generate Project.

Copy the project and unpack it somewhere.

In the build.gradle file, add the following dependency:

implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'

Also while you’re there, notice the dependency com.okta.spring:okta-spring-boot-starter:1.1.0. This is the Okta Spring Boot Starter. It’s a handy project that makes integrating Okta with Spring Boot nice and easy. For more info, take a look at the project’s GitHub.

Change the src/main/resources/application.properties to application.yml and add the following:

server:
port: 8080
okta:
oauth2:
issuer: https://okta.okta.com/oauth2/default
client-id: {yourClientId}
client-secret: {yourClientSecret}
spring:
thymeleaf:
cache: false

Remember when I said you’ll need your ClientID and Client Secret above. Well, the time has come. You need to fill them into the file, as well as your Okta issuer URL. It’s gonna look something like this: dev-123456.okta.com. You can find it under API > Authorization Servers.

You also need two similar template files in the src/main/resources/templates directory. The index.htmltemplate file is exactly the same, and can be copied over if you like. The securedPage.html template file is slightly different because of the way the authentication information is returned from Okta as compared to the simple authentication server you built earlier.

Create the home template: src/main/resources/templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Spring Security SSO</h1>
<a href="securedPage">Login</a>
</body>
</html>

And the secured template: src/main/resources/templates/securedPage.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Secured Page</title>
</head>
<body>
<h1>Secured Page</h1>
<span th:text="${#authentication.principal.attributes.name}">Joe Coder</span>
</body>
</html>

Create a Java class named WebController in the com.okta.spring.SpringBootOAuth package:

package com.okta.spring.OktaOAuthClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.security.Principal;
@Controller
public class WebController {
@RequestMapping("/securedPage")
public String securedPage(Model model, Principal principal) {
return "securedPage";
}
@RequestMapping("/")
public String index(Model model, Principal principal) {
return "index";
}
}

This class simply creates two routes, one for the home route and one for the secured route. Again, Spring Boot and Thymeleaf are auto-magicking this to the two template files in src/main/resources/templates.

Finally, create another Java class names SecurityConfiguration:

package com.okta.spring.OktaOAuthClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
}
}

That’s it! Bam!

Run the Okta-OAuth-powered client:

./gradlew bootRun

You should see a bunch of output that ends with:

...
2019-02-23 20:09:03.465 INFO 55890 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-02-23 20:09:03.470 INFO 55890 --- [ main] c.o.s.O.OktaOAuthClientApplication : Started OktaOAuthClientApplication in 3.285 seconds (JVM running for 3.744)

Navigate to http://localhost:8080.

Click the Login button.

This time, you’ll be directed to the Okta login page. You may need to use an incognito browser or log out of your developer.okta.com dashboard here so that you don’t skip the login page and get directed immediately to the secured endpoint.

Log in, and you’ll see the secured page with your name!

Learn More About Spring Boot, Spring Security, and OAuth 2.0

So, that’s that. Super easy. In the previous tutorial, you looked at how to use Spring Boot and Spring Security to implement a very basic authentication server and client app. Next, you used Okta to make an even simpler client app with fully functioning SSO and OAuth authentication.

You can see the completed code for this tutorial on GitHub at oktadeveloper/okta-spring-boot-authz-server-example.

Originally published by  Andrew Hughes  he at dzone.com

=================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ Learn Ethical Hacking From Scratch

☞ The Complete Cyber Security Course : Hackers Exposed!

☞ Spring & Hibernate for Beginners (includes Spring Boot)

☞ Spring Boot + JPA + Hibernate + Oracle

☞ Building a Web Application Using Spring Boot, Angular, and Maven

☞ Angular 8 + Spring Boot 2.2: Build a CRUD App Today!

☞ Spring Boot vs. Spring MVC vs. Spring: How Do They Compare?

☞ Ethical Hacking With Python, JavaScript and Kali Linux

☞ The Complete Ethical Hacking Course: Beginner to Advanced!

☞ Hacking in Practice: Certified Ethical Hacking MEGA Course

☞ Learn Python & Ethical Hacking From Scratch

☞ The Complete Ethical Hacking Course

☞ Advance Web Hacking : Penetration Testing & Bug Bounty

Build a Spring Boot App With Secure Server-to-Server Communication via OAuth 2.0

Build a Spring Boot App With Secure Server-to-Server Communication via OAuth 2.0

How to build a Spring Boot App for server-to-server communication via the OAuth 2.0 Client Credentials Grant type.

Most OAuth 2.0 guides are focused around the context of a user, i.e. logging in to an application using Google, Github, Okta, etc. While this can be useful, these guides ignore server-to-server communication where there is no user and you only have one service connecting to another. Thankfully, Okta is here to lend a hand with this area of application security.

The OAuth 2.0 Client Credentials Grant type is exclusively used for scenarios in which no user exists (CRON jobs, scheduled tasks, other data workloads, etc.). This flow is less showy than other OAuth flows as there is no end user or browser. However, this is far easier to understand than the more complicated, user-centric OAuth 2.0 grant types. In this tutorial, we'll walk through the OAuth 2.0 Client Credentials Grant type and how you can deploy it for secure server-to-server communication in Spring Boot.

OAuth 2.0 Client Credentials Grant

The goal of the Client Credentials Grant is to allow two machines to communicate securely. In this grant type, you have a client (think of this as your application) making API requests to another service (this is your resource server).

To help illustrate why this flow is important, let’s take a step back and talk about what we did before OAuth 2.0.

NOTE: If you’re an OAuth pro, you can skip ahead to the code examples below or check out this example on GitHub.

Before OAuth 2.0, the way developers handled server-to-server authentication was with HTTP Basic Auth. Essentially, this boiled down to a developer that would send over a server’s unique username and password (often referred to as an ID and secret) on each request. The API service would then validate this username and password on every request by connecting to a user store (database, LDAP, etc.) in order to validate the credentials.

This approach has a few drawbacks and exposure points:

  • Each application in the diagram above handles the username and password.
  • A second username and password might be needed to connect to the user store.
  • The same username and password is used for each request.

There are various ways to help mitigate these risks, but that’s out of scope in this post.

The OAuth 2.0 Client Credentials Grant was created to help solve the problems that originated with HTTP Basic Auth. While the client still uses a username and password (called the clientid and clientsecret), instead of sending them directly to the API service on each request, they are instead exchanged for a token via an authorization server.

The authorization server returns a temporary access token (which is used until it expires). The client then uses this access token when communicating with the resource server, which means that your client’s most sensitive data (the ID and secret) are only shared over the network once every expiration period, dramatically reducing the likelihood of compromise. Once the resource server receives the incoming request with the access token, it will then validate the token with by talking to the authorization server.

I’ll talk about a couple of ways to reduce the number of network calls further at the end of this post, but, first, onto an example!

Let’s Build an OAuth 2.0 Client Credentials App!

Enough talk, let’s do something! I’m going to show you how to implement the Client Credentials Grant type with Spring using two applications: a client and server. The server will have a single endpoint which returns a “message of the day.” The client will be a simple command line application; you could easily replace this with a backend web application, CRON job, or any other backend script.

Set Up Your Authorization Server

To keep things simple, you’ll use Okta to create an OAuth 2.0 authorization server. This will handle all of the Client Credentials Grant stuff mentioned above. Do you need to use Okta? Not at all! You can use any OAuth 2.0 compatible server that you want. But, because our service is free and simple to use, it speeds up this process.

If you don’t already have a free developer account, head over to developer.okta.com and click Sign Up. When that’s complete, you’ll have two pieces of information, your Okta base URL, which looks something like: dev-123456.oktapreview.com, and an email with instructions on how to activate your account.

After activating your account, while you are still in the Okta Developer Console, you then need to create an application and a custom OAuth scope. The application will give you a client ID and secret, while the custom scope will restrict your access token to this example.

Click the Applications menu item, then Add Application.  Next, select Service -> Next. You will then change the name to whatever you want (I’m going to use “My MOD App”). Next, click Done.

You will need the Client ID and Client secret values for the next steps.

Then, create a custom scope for your application.

From the menu bar, select API -> Authorization Servers. Remember the Issuer URI value; you will need this for the following steps. Edit the authorization server by clicking on the edit pencil, then click Scopes -> Add Scope. Fill out the name field with custom_mod and press Create.

Now, onto the fun stuff!

Create a Resource Server

This resource server (aka: API service) is going to be overly simple and consist of a single /mod endpoint. Now, create a new project using the Spring Initializer on the command line:

curl https://start.spring.io/starter.tgz  \
  -d artifactId=creds-example-server \
  -d dependencies=security,web \
  -d language=java \
  -d type=maven-project \
  -d baseDir=creds-example-server \
| tar -xzvf -
change into the new directory

cd creds-example-server

You will also need to manually add one more dependency to your pom.xml:

<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

NOTE: I also renamed the DemoApplication to ServerApplication , because we are going to create another application shortly.

Next, update the ServerApplication to include the @EnableResourceServer annotation and add a simple REST controller:

@EnableResourceServer
@SpringBootApplication
public class ServerApplication {

public static void main(String[] args) {
    SpringApplication.run(ServerApplication.class, args);
}

/**
 * Allows for @PreAuthorize annotation processing.
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
protected static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

@RestController
public class MessageOfTheDayController {
    @GetMapping("/mod")
    @PreAuthorize("#oauth2.hasScope('custom_mod')")
    public String getMessageOfTheDay(Principal principal) {
        return "The message of the day is boring for user: " + principal.getName();
    }
}

}

Now it is time to configure the application! I renamed my application.properties file to application.yml and updated it to include:

security:
oauth2:
client:
clientId: {client-id-from-above}
clientSecret: {client-secret-from-above}
resource:
tokenInfoUri: {issuer-uri-from-above}/v1/introspect

That’s it! Just a few lines of code and a couple lines of config! Spring Boot will automatically handle the validation of the access tokens — all you need to do now is worry about is your code!

Next, start it up and leave it running:

./mvn spring-boot:run

You can try to access http://localhost:8080/mod , if you want. It will respond with HTTP 401 UNAUTHORIZED.

Create the OAuth 2.0 Client

Next, you’re going to create a simple command-line client (you could easily duplicate this logic in any type of application).

Next, open up a new terminal window and create a second application with the Spring Initializer:

curl https://start.spring.io/starter.tgz  
-d artifactId=creds-example-client
-d dependencies=security
-d language=java
-d type=maven-project
-d baseDir=creds-example-client
| tar -xzvf -

change into the new directory

cd creds-example-client

This will follow the same instructions as before — add in the Spring OAuth 2.0 library as a dependency in your pom.xml:

<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

This time, I’ll start by defining the configuration

(again I renamed application.properties to application.yml):

example:
baseUrl: http://localhost:8080
oauth2:
client:
grantType: client_credentials
clientId: {client-id-from-above}
clientSecret: {client-secret-from-above}
accessTokenUri: {issuer-uri-from-above}/v1/token
scope: custom_mod

I’ve namespaced the configuration under example since you could be connecting to multiple servers.

I configured a few properties:

  • baseUrl is the base URL of our example server
  • grantType defines the grant type for the connection
  • clientId and clientSecret are the same as above
  • accessTokenUri defines the URI used to get an access token
  • scope is the custom scope we created above

Last up is our ClientApplication (renamed from DemoApplication):

@SpringBootApplication
public class ClientApplication implements CommandLineRunner {
private final Logger logger = LoggerFactory.getLogger(ClientApplication.class);
@Value("#{ @environment['example.baseUrl'] }")
private String serverBaseUrl;
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
@Bean
@ConfigurationProperties("example.oauth2.client")
protected ClientCredentialsResourceDetails oAuthDetails() {
return new ClientCredentialsResourceDetails();
}
@Bean
protected RestTemplate restTemplate() {
return new OAuth2RestTemplate(oAuthDetails());
}
@Override
public void run(String... args) {
logger.info("MOD: {}", restTemplate().getForObject(serverBaseUrl + "/mod", String.class));
}
}

There are a few items that I want to touch on:

  • The CommandLineRunner interface adds a run method, which is called automatically after initialization. The application exits after leaving this method.
  • I created an ClientCredentialsResourceDetails bean, which is bound to my configuration properties: example.oauth2.client . 
  • I used an OAuth2RestTemplate in place of a standard RestTemplate . This automatically manages all of the OAuth 2.0 access token exchange and sets the Authentication: Bearer header value. Basically, it handles all of the OAuth detail so you don’t need to worry about any of them!

Next, run the application with ./mvnw spring-boot:run and you should see a console output similar to:

2018-03-20 12:56:10.058  INFO 15833 --- [main] c.e.c.ClientApplication: MOD: The message of the day is boring for user: 0oabcd12yz2EpHuis75s3

The client has successfully communicated with the server! Not bad, right? In just a few lines of code, you were able to get an OAuth 2.0 authorization server setup and configured, as well as create two Spring apps (one client and one server) that can now communicate securely using the OAuth 2.0 Client Credentials Grant type!

NOTE: if you see a 401 or 500 exception, double check that your application.yml config files contain the correct information.

Extra Credit: Reduce the Number of Calls to the Authorization Server

The second sequence diagram above seems more complicated than the first, even when factoring in the reuse of an access token. Access tokens are opaque. There is no spec behind them, and the format is left to the implementation of the authorization server.

At Okta, we use signed JWTs, which means you can validate them locally, instead of making an additional request from the API service to the authorization server on each request.

We have helper libraries in a few different languages and a Spring Boot starter that will handle the local validation for you.

Thanks for reading! If you liked this post, share it with all of your programming buddies!

Originally published on https://dzone.com


Spring Boot Tutorial For Beginner- Spring Boot Full Course

Spring Boot Tutorial For Beginner- Spring Boot Full Course

This "Spring Boot Tutorial For Beginner- Spring Boot Full Course" video will help you learn Spring Boot Framework from scratch with examples. This Spring Tutorial is ideal for both beginners as well as professionals who want to master the Spring Boot Framework

Spring Boot Full Course - Learn Spring Boot In 4 Hours | Spring Boot Tutorial For Beginner

Below are the topics covered in this Spring Boot Tutorial for Beginners video:

1:40 What is Spring Boot?
2:35 Features of Spring Boot
3:50 Why Do We Need Spring Boot?
4:30 Spring Boot Market Trend
5:15 Spring vs Spring Boot
6:25 Install & Setup Spring Boot
6:45 System Requirements
7:35 Install & Set up Spring Boot CLI
14:00 Install & Setup Spring Tool Suite
25:40 Model View Controller
26:00 What is MVC?
27:35 Model View Controller Workflow
29:00 What is Dependency Injection?
31:50 Inversion of Control
33:10 Types of Dependency Injection
34:05 Benefits of Dependency Injection
48:35 Auto wire
49:50 Create First Web Application Using Spring Boot
1:06:50 Create a Web Application To Pass Client Data
1:13:40 Model View & Object Example
1:20:30 Create a Submission Form In Spring Boot
1:40:50 Connect Web Application To Database
2:04:50 REST API
2:07:35 What is REST API?
2:08:50 Features of REST API
2:09:35 Principles of REST API
2:11:40 Methods of REST API
2:12:20 REST API Hands-On
2:35:55 Spring Data REST
2:36:55 Spring Data REST Hands-On
2:46:35 Spring Security
2:47:30 Secure Applications Using Spring Boot
2:58:56 Spring Boot Interview Questions