在本教程中,咱们将讨论如何使用 Spring Security OAuth 和 Spring Boot 实现 SSO(单点登陆)。html
本示例将使用到三个独立应用前端
简而言之,当用户尝试访问客户端应用的安全页面时,他们首先经过身份验证服务器重定向进行身份验证。java
咱们将使用 OAuth2 中的 Authorization Code
受权类型来驱动受权。git
先从客户端应用下手,使用 Spring Boot 来最小化配置:github
首先,须要在 pom.xml
中添加如下依赖:web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency>
接下来,最重要的部分就是客户端应用的安全配置:spring
@Configuration @EnableOAuth2Sso public class UiSecurityConfig extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**") .permitAll() .anyRequest() .authenticated(); } }
固然,该配置的核心部分是 @EnableOAuth2Sso
注解,咱们用它来启用单点登陆。安全
请注意,咱们须要继承 WebSecurityConfigurerAdapter
— 若是没有它,全部路径都将被保护 — 所以用户在尝试访问任何页面时将被重定向到登陆页面。 在当前这个示例中,索引页面和登陆页面能够在没有身份验证的状况下能够访问。ruby
最后,咱们还定义了一个 RequestContextListener
bean 来处理请求。服务器
application.yml
:
server: port: 8082 context-path: /ui session: cookie: name: UISESSION security: basic: enabled: false oauth2: client: clientId: SampleClientId clientSecret: secret accessTokenUri: http://localhost:8081/auth/oauth/token userAuthorizationUri: http://localhost:8081/auth/oauth/authorize resource: userInfoUri: http://localhost:8081/auth/user/me spring: thymeleaf: cache: false
有几点须要说明:
accessTokenUri
是获取访问令牌的 URIuserAuthorizationUri
是用户将被重定向到的受权 URIuserInfoUri
URI 用于获取当前用户的详细信息另外须要注意,在本例中,咱们使用了本身搭建的受权服务器,固然,咱们也可使用其余第三方提供商的受权服务器,例如 Facebook 或 GitHub。
如今来看看客户端应用的前端配置。咱们不想把太多时间花费在这里,主要是由于以前已经介绍过了。
客户端应用有一个很是简单的前端:
index.html:
<h1>Spring Security SSO</h1> <a href="securedPage">Login</a>
securedPage.html:
<h1>Secured Page</h1> Welcome, <span th:text="${#authentication.name}">Name</span>
securedPage.html
页面须要用户进行身份验证。 若是未通过身份验证的用户尝试访问 securedPage.html
,他们将首先被重定向到登陆页面。
如今让咱们开始来讨论受权服务器。
首先,在 pom.xml
中定义依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency>
理解咱们为何要在这里将受权服务器和资源服务器做为一个单独的可部署单元一块儿运行这一点很是重要。
让咱们从配置资源服务器开始探讨:
@SpringBootApplication @EnableResourceServer public class AuthorizationServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(AuthorizationServerApplication.class, args); } }
以后,配置受权服务器:
@Configuration @EnableAuthorizationServer public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("SampleClientId") .secret("secret") .authorizedGrantTypes("authorization_code") .scopes("user_info") .autoApprove(true) ; } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } }
须要注意的是咱们使用 authorization_code
受权类型来开启一个简单的客户端。
首先,咱们将经过 application.properties
禁用默认的 Basic Authentication:
server.port=8081 server.context-path=/auth security.basic.enabled=false
如今,让咱们到配置定义一个简单的表单登陆机制:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @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.parentAuthenticationManager(authenticationManager) .inMemoryAuthentication() .withUser("john").password("123").roles("USER"); } }
请注意,虽然咱们使用了简单的内存认证,但能够很简单地将其替换为自定义的 userDetailsService
。
最后,咱们将建立以前在配置中使用到的用户端点:
@RestController public class UserController { @GetMapping("/user/me") public Principal user(Principal principal) { return principal; } }
用户数据将以 JSON 形式返回。
在这篇快速教程中,咱们使用 Spring Security Oauth2 和 Spring Boot 实现了单点登陆。
一如既往,您能够在 GitHub 上找到完整的源码。
本文转载自
原文做者:云栖路
原文连接:https://blog.csdn.net/s573626822/article/details/79870244