SpringSecurity中怎么利用OAuth2实现单点登录功能
创始人
2024-12-21 09:41:44
0次

1.概述

•授权服务器 - 这是中央身份验证机制•两个客户端应用程序:使用SSO的应用程序

非常简单地说,当用户试图访问客户端应用程序中的安全页面时,他们将被重定向到首先通过身份验证服务器进行身份验证。

我们将使用OAuth3中的授权代码授权类型来驱动身份验证委派。

2.客户端应用程序

让我们从客户端应用程序开始;当然,我们将使用Spring Boot来最小化配置:

2.1。 Maven依赖

首先,我们需要在pom.xml中使用以下依赖项:

org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-security org.springframework.security.oauth.boot spring-security-oauth3-autoconfigure 2.0.1.RELEASE org.springframework.boot spring-boot-starter-thymeleaf org.thymeleaf.extras thymeleaf-extras-springsecurity4

2.2。Security配置

接下来,最重要的部分,我们的客户端应用程序的Security配置:

@Configuration@EnableOAuth3Ssopublic class UiSecurityConfig extends WebSecurityConfigurerAdapter {   @Override public void configure(HttpSecurity http) throws Exception {  http.antMatcher("/**")   .authorizeRequests()   .antMatchers("/", "/login**")   .permitAll()   .anyRequest()   .authenticated(); }}

当然,这种配置的核心部分是我们用于启用单点登录的@ EnableOAuth3Sso注释。

请注意,我们需要扩展WebSecurityConfigurerAdapter - 如果没有它,所有路径都将受到保护 - 因此用户将在尝试访问任何页面时重定向以登录。在我们的例子中,首页和登录页面是唯一可以在没有身份验证的情况下访问的页面。

最后,我们还定义了一个RequestContextListener bean来处理请求范围。

application.yml:server: port: 8082 servlet:  context-path: /ui session:  cookie:  name: UISESSIONsecurity: basic: enabled: false oauth3: 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/mespring: thymeleaf: cache: false

一些快速说明:

•我们禁用了默认的基本身份验证•accessTokenUri是获取访问令牌的URI•userAuthorizationUri是用户将被重定向到的授权URI•userInfoUri用户端点的URI,用于获取当前用户详细信息

另请注意,在我们的示例中,我们推出了授权服务器,但当然我们也可以使用其他第三方提供商,如Facebook或GitHub。

2.3。前端

现在,让我们来看看客户端应用程序的前端配置。我们不会在这里专注于此,主要是因为我们已经在网站上介绍过。我们的客户端应用程序有一个非常简单的前端;这是index.html:

Spring Security SSO

Login

和securedPage.html:

Secured Page

Welcome, Name

securedPage.html页面需要对用户进行身份验证。如果未经身份验证的用户尝试访问securedPage.html,则会首先将其重定向到登录页面。

3. Auth服务器

现在让我们在这里讨论我们的授权服务器。

3.1。 Maven依赖

首先,我们需要在pom.xml中定义依赖项:

org.springframework.boot spring-boot-starter-web org.springframework.security.oauth spring-security-oauth3 2.3.3.RELEASE

3.2。 OAuth配置

重要的是要理解我们将在这里一起运行授权服务器和资源服务器,作为单个可部署单元。

让我们从资源服务器的配置开始 :

@SpringBootApplication@EnableResourceServerpublic class AuthorizationServerApplication extends SpringBootServletInitializer { public static void main(String[] args) {  SpringApplication.run(AuthorizationServerApplication.class, args); }}

然后,我们将配置我们的授权服务器:

@Configuration@EnableAuthorizationServerpublic class AuthServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private BCryptPasswordEncoder 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("SampleClientId")   .secret(passwordEncoder.encode("secret"))   .authorizedGrantTypes("authorization_code")   .scopes("user_info")   .autoApprove(true)    .redirectUris("http://localhost:8082/ui/login","http://localhost:8083/ui2/login");  }}

请注意我们如何仅使用authorization_code grant类型启用简单客户端。

另外,请注意autoApprove如何设置为true,以便我们不会被重定向并手动批准任何范围。

3.3。Security配置

首先,我们将通过application.properties禁用默认的基本身份验证:

server.port=8081server.servlet.context-path=/auth

现在,让我们转到配置并定义一个简单的表单登录机制:

@Configuration@Order(1)public class SecurityConfig extends WebSecurityConfigurerAdapter {  @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("john")   .password(passwordEncoder().encode("123"))   .roles("USER"); }   @Bean public BCryptPasswordEncoder passwordEncoder(){   return new BCryptPasswordEncoder();  }}

请注意,我们使用简单的内存中身份验证,但我们可以简单地将其替换为自定义userDetailsService。

3.4。用户端

最后,我们将创建我们之前在配置中使用的用户端:

@RestControllerpublic class UserController { @GetMapping("/user/me") public Principal user(Principal principal) {  return principal; }}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...