SpringBoot SSO整合

SpringBoot整合SSO教程

提示:如有疑问请私信联系、下方有源代码地址,请自行拿取


前言

网上SSO的框架很多,此篇文章使用的是自写的SSO来实现简单的登录授权功能,目的在于扩展性,权限这方面,自写扩展性会好点。


提示:以下是本篇文章正文内容,下面案例可供参考

一、技术介绍

1.SSO是什么?

单点登录(SingleSignOn,SSO),就是通过用户的一次性鉴别登录。当用户在身份认证服务器上登录一次以后,即可获得访问单点登录系统中其他关联系统和应用软件的权限,同时这种实现是不需要管理员对用户的登录状态或其他信息进行修改的,这意味着在多个应用系统中,用户只需一次登录就可以访问所有相互信任的应用系统。这种方式减少了由登录产生的时间消耗,辅助了用户管理,是目前比较流行的。

二、使用步骤

1.引入maven库

代码如下(示例):

	 	<parent>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-parent</artifactId>
	        <version>2.4.1</version>
	        <relativePath/>
	    </parent>
     <dependencies>
       <dependencies>
        <dependency>
            <artifactId>hyh-boot-starter-redis</artifactId>
            <groupId>com.hyh.redis</groupId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

2.具体使用示例

ILogin接口:

package com.hyh.sso;

import com.hyh.sso.po.LoginResult;

/**
 * 登录接口
 *
 * @Author: heyuhua
 * @Date: 2021/1/8 17:14
 */
public interface ILogin {
   

    /**
     * 登录
     *
     * @param account     用户名
     * @param password    密码
     * @param callbackUrl 用户验证回调URL
     * @return
     */
    LoginResult login(String account, String password, String callbackUrl);


}

登录状态枚举:

package com.hyh.sso;

/**
 * 登录状态枚举
 *
 * @Author: heyuhua
 * @Date: 2021/1/8 16:59
 */
public enum LoginStatus {
   

    SUCCESS(1, "登录成功"), ING(0, "登录中"), FAIL(-1, "登录失败"),
    ERROR(-2, "登录异常"), CALLBACK_ERROR(-3, "登录回调异常"), ACCOUNT_LOCK(-4, "账户被锁定"),
    EXPIRE(-5,"登录用户已过期");
    /**
     * 登录状态码
     */
    private int code;
    /**
     * 登录状态消息
     */
    private String message;


    private LoginStatus(int code, String message) {
   
        this.code = code;
        this.message = message;
    }


    public int getCode() {
   
        return code;
    }

    public void setCode(int code) {
   
        this.code = code;
    }

    public String getMessage() {
   
        return message;
    }

    public void setMessage(String message) {
   
        this.message = message;
    }
    }


登录类型枚举:

package com.hyh.sso;

/**
 * 登录类型
 *
 * @Author: heyuhua
 * @Date: 2021/1/8 17:16
 */
public enum LoginTypes {
   

    /**
     * 登入
     */
    IN,
    /**
     * 登出
     */
    OUT;

}

登录常规接口:

package com.hyh.sso;

package com.hyh.sso.service;

import com.hyh.sso.ILogin;

/**
 * 常规登录接口
 *
 * @Author: heyuhua
 * @Date: 2021/1/8 17:54
 */
public interface LoginService extends ILogin {
   

}

登录接口实现:

package com.hyh.sso.service.impl;

import com.alibaba.fastjson.JSON;
import com.hyh.sso.LoginStatus;
import com.hyh.sso.po.LoginResult;
import com.hyh.sso.po.LoginUser;
import com.hyh.sso.service.LoginService;
import org.slf4j
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Security是Spring框架的一个模块,提供了认证(Authentication)和授权(Authorization)的功能,而OAuth2是一种授权框架,它允许用户授权第三方应用访问其资源,而无需将用户名和密码提供给第三方应用。Spring Security可以与OAuth2进行整合,以实现安全的授权机制。 下面是Spring Boot与Spring Security整合OAuth2的步骤: 1.添加依赖 在pom.xml文件中添加Spring Security和OAuth2的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.0.RELEASE</version> </dependency> ``` 2.配置OAuth2认证服务器 在Spring Boot的配置文件application.yml中添加OAuth2认证服务器的配置信息,如下所示: ``` security: oauth2: client: clientId: client_id clientSecret: client_secret accessTokenUri: http://localhost:8080/oauth/token userAuthorizationUri: http://localhost:8080/oauth/authorize resource: userInfoUri: http://localhost:8080/user ``` 其中,clientId和clientSecret是OAuth2客户端的标识和密码,accessTokenUri和userAuthorizationUri是OAuth2认证服务器的地址,userInfoUri是获取用户信息的地址。 3.配置Spring Security 在Spring Security的配置类中配置OAuth2的授权机制,如下所示: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private ClientDetailsService clientDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin").password("admin").roles("ADMIN") .and() .withUser("user").password("user").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin().permitAll() .and() .logout().permitAll(); } @Bean public TokenStore tokenStore() { return new InMemoryTokenStore(); } @Bean @Autowired public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception { TokenApprovalStore approvalStore = new TokenApprovalStore(); approvalStore.setTokenStore(tokenStore); return approvalStore; } @Bean @Autowired public TokenServices tokenServices(ClientDetailsService clientDetailsService, TokenStore tokenStore) { DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setClientDetailsService(clientDetailsService); tokenServices.setTokenStore(tokenStore); tokenServices.setSupportRefreshToken(true); return tokenServices; } @Bean @Autowired public OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint(ResourceServerProperties sso) { OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint(); entryPoint.setRealmName("spring-boot"); return entryPoint; } @Bean @Autowired public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler(ResourceServerProperties sso) { OAuth2AccessDeniedHandler handler = new OAuth2AccessDeniedHandler(); return handler; } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override @Autowired protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder()); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Autowired public ClientDetailsService clientDetailsService(DataSource dataSource) { return new JdbcClientDetailsService(dataSource); } @Configuration @EnableAuthorizationServer protected static class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter { @Autowired private TokenStore tokenStore; @Autowired private ApprovalStore approvalStore; @Autowired private ClientDetailsService clientDetailsService; @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(clientDetailsService); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore) .approvalStore(approvalStore) .authenticationManager(authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.realm("spring-boot"); } } } ``` 其中,configure方法用于配置Spring Security的授权机制,tokenStore方法用于配置OAuth2的Token存储方式,approvalStore方法用于配置OAuth2的授权信息存储方式,tokenServices方法用于配置OAuth2的Token服务,oAuth2AuthenticationEntryPoint方法用于配置OAuth2的认证入口点,oAuth2AccessDeniedHandler方法用于配置OAuth2的拒绝访问处理器,authenticationManagerBean方法用于获取Spring Security的认证管理器,clientDetailsService方法用于配置OAuth2的客户端信息存储方式,OAuth2AuthorizationConfig类用于配置OAuth2的授权服务器。 4.测试 启动Spring Boot应用程序,打开浏览器,输入URL http://localhost:8080/login,进入登录页面,输入用户名和密码,点击登录按钮,进入首页,此时已经完成了OAuth2的授权机制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

消灭知识盲区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值