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

A case study of spring oauth2 + springboot sso

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "the case study of spring oauth2 + springboot sso". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the case study of spring oauth2 + springboot sso.

First, rely on org.springframework.security.oauth.boot spring-security-oauth3-autoconfigure 2.1.6.RELEASE II, server

1. What the server needs is authorization and authentication. Configure @ EnableAuthorizationServer, @ EnableWebSecurity, @ EnableResourceServer to complete the configuration.

two。 Let's first configure the configuration of WebSecurity

Package com.example.oauth;import org.springframework.boot.autoconfigure.security.SecurityProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.BeanIds;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.builders.WebSecurity Import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.provisioning.InMemoryUserDetailsManager / * @ author sorata * @ date 2019-07-23 09:19 * / @ Configuration@EnableWebSecurity@Order (SecurityProperties.BASIC_AUTH_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@ Bean public UserDetailsService myUserDetailsService () {return new InMemoryUserDetailsManager (User.builder (). Username ("admin") .password (passwordEncoder (). Encode ("admin")). Roles ("ADMIN"). Build ();} @ Bean public BCryptPasswordEncoder passwordEncoder () {return new BCryptPasswordEncoder () } @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService (myUserDetailsService ()) .passwordEncoder (passwordEncoder ());} @ Bean (BeanIds.AUTHENTICATION_MANAGER) @ Override public AuthenticationManager authenticationManagerBean () throws Exception {return super.authenticationManagerBean ();} @ Override public void configure (WebSecurity web) throws Exception {super.configure (web) } @ Override protected void configure (HttpSecurity http) throws Exception {http.csrf () .disable () .antMatcher ("/ * *") .authorizeRequests () .antMatrices ("/", "/ login") "/ oauth/**") .permitAll () .anyRequest () .authenticated () .and () .httpBasic () .and () .formLogin () .and () .logout () }}

Note: first configure the user UserDetailsService, and then configure the password policy. The main part is the configure (HttpSecurity http) method. Here, when I configure verification completion forwarding after formLogin (), that is, after successForwardUrl ("/ main"), when the sso client request verification is completed, it will not jump to the client's request address, but to the server address / main where the verification is successful.

3. Write a controller of user information

Package com.example.oauth;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.security.Principal;/** * @ author sorata * @ date 2019-07-23 09:17 * / @ RestControllerpublic class UserController {@ RequestMapping ("/ user") public Principal principal (Principal principal) {return principal;} @ RequestMapping ("/ user2") public Principal principal2 (Principal principal) {return principal;}}

Note: the function is to test and then url the server user information filled in by the client.

4. Resource server

Package com.example.oauth;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.oauth3.config.annotation.web.configuration.EnableResourceServer;import org.springframework.security.oauth3.config.annotation.web.configuration.ResourceServerConfigurerAdapter / * @ author sorata * @ date 2019-07-23 09:50 * / @ Configuration@EnableResourceServerpublic class ResourceConfig extends ResourceServerConfigurerAdapter {@ Override public void configure (HttpSecurity http) throws Exception {http.csrf () .disable () .antMatcher ("/ user") .authorizeRequests (). AnyRequest (). Authenticated ();}}

5. The effect after completion

6. Important authentication server

Package com.example.oauth;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.oauth3.config.annotation.configurers.ClientDetailsServiceConfigurer;import org.springframework.security.oauth3.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter Import org.springframework.security.oauth3.config.annotation.web.configuration.EnableAuthorizationServer;import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;import org.springframework.security.oauth3.provider.token.TokenStore;import org.springframework.security.oauth3.provider.token.store.InMemoryTokenStore;/** * @ author sorata * @ date 2019-07-23 10:06 * / @ Configuration@EnableAuthorizationServerpublic class SsoServerConfig extends AuthorizationServerConfigurerAdapter {@ Autowired private AuthenticationManager authenticationManager @ Autowired private BCryptPasswordEncoder passwordEncoder; / * if there is an error, remove the default configuration on the main class * {@ link SsoServerApplication} * / @ Autowired private UserDetailsService detailsService; @ Override public void configure (AuthorizationServerSecurityConfigurer security) throws Exception {security.allowFormAuthenticationForClients () .tokenKeyAccess ("permitAll ()") .checkTokenAccess ("isAuthenticated ()") .passwordEncoder (passwordEncoder) } @ Override public void configure (ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory () .withClient ("cocos") .secret (passwordEncoder.encode ("cocos")) .autoApps (true) .redirectUris ("http://localhost:9090/client/login") .scopes (" all ") .authorities (" ADMIN ") ") .authorizedGrantTypes (" authorization_code " "password", "refresh_token") .accessTokenValiditySeconds (10000) .refreshTokenValiditySeconds (10000) } @ Override public void configure (AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager (authenticationManager) .userDetailsService (detailsService) .tokenStore (tokenStore ());} @ Bean public TokenStore tokenStore () {return new InMemoryTokenStore ();}} III. Client

1. The client implementation is relatively simple, if you want to modify the row, you can customize it according to the following reference address.

2.application.properties

Security.oauth3.client.authentication-scheme=formsecurity.oauth3.client.user-authorization-uri= http://localhost:8080/server/oauth/authorizesecurity.oauth3.client.access-token-uri=http://localhost:8080/server/oauth/tokensecurity.oauth3.client.client-id=cocossecurity.oauth3.client.client-secret=cocossecurity.oauth3.resource.user-info-uri=http://localhost:8080/server/userserver.servlet.context-path=/clientserver.port=9090

3. Add comments to the main class

Package com.example.oauth;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.security.oauth3.client.EnableOAuth3Sso;@SpringBootApplication@EnableOAuth3Ssopublic class SsoClientApplication {public static void main (String [] args) {SpringApplication.run (SsoClientApplication.class, args);}}

4. User's interface

Package com.example.oauth;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.security.Principal;/** * @ author sorata * @ date 2019-07-23 10:30 * / @ RestControllerpublic class UserController {@ RequestMapping ("/ user") public Principal principal (Principal principal) {return principal;} IV. Effect

Note: if you want to see

At this point, I believe you have a deeper understanding of the "case study of spring oauth2 + springboot sso". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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