Home > Java > javaTutorial > Using Spring Security OAuth for secure authorization in Java API development

Using Spring Security OAuth for secure authorization in Java API development

WBOY
Release: 2023-06-18 08:01:27
Original
1754 people have browsed it

A common requirement in Java API development is to implement user authentication and authorization functions. In order to provide more secure and reliable API services, the authorization function has become particularly important. Spring Security OAuth is an excellent open source framework that can help us implement authorization functions in Java APIs. This article will introduce how to use Spring Security OAuth for secure authorization.

  1. What is Spring Security OAuth?

Spring Security OAuth is an extension of the Spring Security framework, which can help us implement OAuth authentication and authorization functions.

OAuth is an open standard for authorizing third-party applications to access resources. It can help us achieve business logic decoupling and secure applications. The OAuth authorization process usually includes the following roles:

  • User: the owner of the resource;
  • Client: the application that applies to access user resources;
  • Authorization server: Server that handles user authorization;
  • Resource server: Server that stores user resources;
  1. Authorization process

Spring Security OAuth implements OAuth Four endpoints in the authorization process:

  • /oauth/authorize: the authorization endpoint of the authorization server;
  • /oauth/token: the token endpoint of the authorization server;
  • /oauth/confirm_access: The endpoint for the client to confirm the authorization;
  • /oauth/error: The endpoint for the authorization server error message;

Spring Security OAuth implements the four aspects of OAuth 2.0 Large authorization mode:

  • Authorization code mode: The usage scenario is that user authorization is required when the application is started;
  • Password mode: The usage scenario is that the client manages user credentials independently;
  • Simplified mode: The usage scenario is that the client runs in the browser, and the client does not need to protect user credentials;
  • Client mode: The usage scenario is that the client does not require user authorization, and the requested access token Only represents the client itself;
  1. Add Spring Security OAuth dependency

Add Spring Security OAuth dependency in the project. Configure the following in pom.xml:

<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.3.4.RELEASE</version>
</dependency>
Copy after login
  1. Configure the authorization server

We need to define the authorization server for authorization. In Spring Security OAuth, you can define an authorization server by enabling an OAuth2 authentication server and implementing the AuthorizationServerConfigurer interface.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    TokenStore tokenStore;

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client")
            .secret("{noop}secret")
            .authorizedGrantTypes("client_credentials", "password")
            .scopes("read", "write")
            .accessTokenValiditySeconds(3600)
            .refreshTokenValiditySeconds(7200);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
            .authenticationManager(authenticationManager);
    }
}
Copy after login

In the above code, we define a memory-based client details service, configure the authorization type as client_credentials and password, and also specify the validity period of the access token and the validity period of the refresh token. Additionally, we define the endpoints and their required tokenStore and authenticationManager.

  1. Configure the resource server

To use Spring Security OAuth security authorization, we also need to configure the resource server. In Spring Security OAuth, we can define resource servers by implementing the ResourceServerConfigurer interface.

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .anyRequest().permitAll();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer config) throws Exception {
        config.resourceId("my_resource_id");
    }
}
Copy after login

In the above code, we defined /api/** to give authentication while other requests allow anonymous access. We also configure the resource ID "my_resource_id" for use in subsequent authorization processes.

  1. Configuring Web Security

In order to use Spring Security OAuth security authorization, we also need to configure Web security. In Spring Security OAuth, security can be defined by implementing the SecurityConfigurer interface.

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("{noop}password")
            .roles("USER");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/oauth/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .permitAll();
    }
}
Copy after login

In the above code, we define a memory-based user details service and declare requests that require authentication (that is, all paths following /oauth/** require authentication, and other paths can be accessed anonymously). We also configured a simple form login for users to log into the application.

  1. Implement UserDetailsService

We need to implement the UserDetailsService interface for use in security authorization. Here we directly use memory to save user accounts and passwords, and do not involve database operations.

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("user".equals(username)) {
            return new User("user", "{noop}password",
                    AuthorityUtils.createAuthorityList("ROLE_USER"));
        } else {
            throw new UsernameNotFoundException("username not found");
        }
    }
}
Copy after login
  1. Implementing API

Next we need to implement a simple API. We added a getGreeting() API under the /api/** path to return a greeting to the client.

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/greeting")
    public String getGreeting() {
        return "Hello, World!";
    }
}
Copy after login
  1. Testing the authorization process

Finally, we need to test whether the authorization process is running as expected. First, we use the authorization code mode to obtain the authorization code:

http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8080&scope=read
Copy after login

Visit the above URL in your browser, you will be asked to enter your username and password for authorization. Enter the username user and password password and click Authorize, you will be redirected to http://localhost:8080/?code=xxx, where xxx is the authorization code.

Next, we use the password pattern to obtain the access token:

curl -X POST 
  http://localhost:8080/oauth/token 
  -H 'content-type: application/x-www-form-urlencoded' 
  -d 'grant_type=password&username=user&password=password&client_id=client&client_secret=secret'
Copy after login

You will receive a JSON response containing the access token and refresh token:

{
    "access_token":"...",
    "token_type":"bearer",
    "refresh_token":"...",
    "expires_in":3600,
    "scope":"read"
}
Copy after login

Now you can use this access token to access the API service:

curl -X GET 
  http://localhost:8080/api/greeting 
  -H 'authorization: Bearer xxx'
Copy after login

where xxx is your access token. You will receive a JSON response containing the greeting "Hello, World!".

In this article, we introduce how to use Spring Security OAuth for secure authorization. Spring Security OAuth is a very powerful framework that can help us implement all roles in the OAuth authorization process. In practical applications, we can choose different authorization modes and service configurations according to different security requirements.

The above is the detailed content of Using Spring Security OAuth for secure authorization in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template