Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use OAuth2.0 to realize authentication in SpringCloud

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What this article shares with you is about how to use OAuth2.0 to achieve authentication in SpringCloud. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

SpringSecurity

Spring Security is a powerful and highly customizable authentication and access control framework. It is used to protect Spring-based applications. Spring Security is a framework that focuses on providing authentication and authorization to Java applications. As with all Spring projects, the real power of Spring security is that it can be easily extended to meet custom needs.

OAuth3.0

OAuth 2.0 is an industry standard protocol for authorization. OAuth3.0 focuses on the simplicity of client developers while providing specific authorization flows for Web applications, desktop applications, mobile phones, and living room devices. Please refer to OAuth3.0 for more.

OAuth3.0 mode

Model application scenario description Authorization Code (Auth Code) jumps to other pages after success, such as third-party Wechat login

Simplified mode (implicit) applies for tokens directly from the authentication server in the browser without going through the server of the third-party application

Password mode (password credentials) web page username password login

Client mode (client credentials) is mainly aimed at openapi, using apikey and secretkey methods

JWT

JSON Web Token (JWT) is the most popular cross-domain authentication solution at present. For more information, please refer to the JWT getting started tutorial

2. Prerequisites

Core pom dependencies are as follows:

Org.springframework.boot spring-boot-starter-security org.springframework.security.oauth spring-security-oauth3 2.3.6.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-security org.slf4j slf4j-api 1.7.25 org.projectlombok lombok

Create a rest interface for later test resources

@ Slf4j@RestControllerpublic class TestSecurityController {@ GetMapping ("/ product/ {id}") public String getProduct (@ PathVariable String id) {/ / for debug Authentication authentication = SecurityContextHolder.getContext () .getAuthentication (); return "product id:" + id;} @ GetMapping ("/ order/ {id}") public String getOrder (@ PathVariable String id) {/ / for debug Authentication authentication = SecurityContextHolder.getContext () .getAuthentication () Return "order id:" + id;}} 3. Operation steps

Many articles are very complicated, in fact, the main content is divided into the following steps

3.1Authorization server AuthorizationServerConfigurerAdapter

You need to customize the license server and inherit AuthorizationServerConfigurerAdapter. The detailed code is as follows

@ Configuration@EnableAuthorizationServerpublic class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {private static final String DEMO_RESOURCE_ID = "order"; @ Autowired AuthenticationManager authenticationManager; @ Autowired RedisConnectionFactory redisConnectionFactory; @ Override public void configure (ClientDetailsServiceConfigurer clients) throws Exception {/ / configure two clients, one for password authentication and one for client authentication String secret = new BCryptPasswordEncoder () .encode ("123456") / / encrypt a pair of passwords clients.inMemory (). WithClient ("client_1") .resourceIds (DEMO_RESOURCE_ID) .authorizedGrantTypes ("client_credentials") "refresh_token") .scopes ("select") .authorities ("client") .secret (secret) .and (). WithClient ("client_2") .resourceIds (DEMO_RESOURCE_ID) .authorizedGrantTypes ("password") "refresh_token") .scopes ("select") .authorities ("client") .secret (secret) } @ Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints .tokenStore (new RedisTokenStore (redisConnectionFactory)) .authenticationManag er (authenticationManager);} @ Override public void configure (AuthorizationServerSecurityConfigurer oauthServer) throws Exception {/ / allow form authentication oauthServer.allowFormAuthenticationForClients ();}} 3.2.Resource server ResourceServerConfigurerAdapter

As above, you need to implement your own resource server and inherit ResourceServerConfigurerAdapter. The detailed code is as follows

@ Configuration@EnableResourceServerpublic class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {private static final String DEMO_RESOURCE_ID = "order"; @ Override public void configure (ResourceServerSecurityConfigurer resources) {resources.resourceId (DEMO_RESOURCE_ID) .stateless (true) } @ Override public void configure (HttpSecurity http) throws Exception {/ / @ formatter:off http / / Since we want the protected resources to be accessible in the UI as well we need / / session creation to be allowed (it's disabled by default in 2.0.6) .sessionManagement () .sessionCreationPolicy (SessionCreationPolicy.IF_REQUIRED) .and ( ) .requestMatrices (). AnyRequest () .and () .authorizeRequests () / / .antMatrices ("/ product/**"). Access ("# oauth3.hasScope ('select') and hasRole (' ROLE_USER')") .antMatch ("/ order/**") .authenticated () / / configure order access control, must be authenticated before accessing / / @ formatter:on}} 3.3.Configuring SpringSecurity@Configuration@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {@ Bean @ Override protected UserDetailsService userDetailsService () {InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager (); String pwd = new BCryptPasswordEncoder () .encode ("123456") / / A pair of passwords are encrypted manager.createUser (User.withUsername ("user_1") .password (pwd) .authorities ("USER") .build (); manager.createUser (User.withUsername ("user_2") .password (pwd) .authorities ("USER") .build (); return manager } @ Override protected void configure (HttpSecurity http) throws Exception {http .requestMatrices (). AnyRequest () .and () .authorizeRequests () .antMatrices ("/ oauth/*"). PermitAll (); @ Bean @ Override public AuthenticationManager authenticationManagerBean () throws Exception {AuthenticationManager manager = super.authenticationManagerBean (); return manager } @ Bean PasswordEncoder passwordEncoder () {return new BCryptPasswordEncoder ();}} 4, Test

We designed that the product service can be accessed anonymously, while the order service needs a signature to access it. The verification is as follows:

The password mode uses postman for post access to http://localhost:8080/oauth/token?username=user_1&password=123456&grant_type=password&scope=select&client_id=client_2&client_secret=123456 to get the following results

{"access_token": "c2340190-48f3-4291-bb17-1e4d51bcb284", "token_type": "bearer", "refresh_token": "03ee113c-a942-452a-9918-7ffe24472a7f", "expires_in": 40399, "scope": "select"}

The client mode also uses postman's POST method to access http://localhost:8080/oauth/token?grant_type=client_credentials&scope=select&client_id=client_1&client_secret=123456. The results are as follows

{"access_token": "05a4e614-f34b-4c83-9ec1-89ea55c0afd2", "token_type": "bearer", "expires_in": 40396, "scope": "select"}

Access to resources

Product service: visit http://localhost:8080/product/1 to get the following data

Product id: 1

Order service: access http://localhost:8080/order/1 and return data as follows

Full authentication is required to access this resourceunauthorized

The verification result indicates that the order service needs a signature before it can be accessed. Next, we enter a signature to access the order service. We respectively use the token obtained by the above password mode to access http://localhost:8080/order/1?access_token=c2340190-48f3-4291-bb17-1e4d51bcb284 to get the data order id: 1

General use of client mode to obtain token, access to http://localhost:8080/order/1?access_token=05a4e614-f34b-4c83-9ec1-89ea55c0afd2 can also get order id: 1

The above is how to use OAuth2.0 to achieve authentication in SpringCloud. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report