【SpringSecurity OAuth2 JWT】实现SSO单点登录(四)

一、 概述

本文使用Springsecurity、Oauth2 + JWT实现单点登录功能。

承接上一篇文章:《第三篇》

本文介绍实现 SSO Client端 相关代码。

二、代码参考

  1. Client端 :

  • pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <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.3.RELEASE</version>
        </dependency>
  • WebSecurityConfigurerAdapter 拦截器
  • @EnableOAuth2Sso 注释主要实现了以下功能

1. 添加@EnableOAuth2Client
2. 启用OAuth2 SSO相关的OAuth2SsoProperties配置文件
3. 导入了3个配置类:OAuth2SsoDefaultConfiguration、OAuth2SsoCustomConfiguration、ResourceServerTokenServicesConfiguration

@EnableOAuth2Sso
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${exit_url}")
    private String exit_url;

    @Autowired
    @Qualifier("resourceServerRequestMatcher")
    private RequestMatcher resources;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        RequestMatcher nonResoures = new NegatedRequestMatcher(resources);
        http.requestMatcher(nonResoures).authorizeRequests()
                .antMatchers("/static/**", "/swagger-ui.html/**", "/swagger-resources/**",
                        "/webjars/**", "/v2/**", "/error", "/css/**", "/js/**", "/fonts/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl(exit_url)
                .and()
                .cors()
                .and()
                .csrf().disable();
    }

}
  • ResourceServerConfigurerAdapter 资源服务器

  • 与服务端程序相似,拦截api相关接口

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Bean("resourceServerRequestMatcher")
    public RequestMatcher resources() {
        return new AntPathRequestMatcher("/api/**");
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(resources()).authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .cors()
                .and()
                .csrf().disable();
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
        resources.tokenServices(tokenServices());
    }

    @Bean
    @Primary
    public JwtTokenStore jwtTokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    @Primary
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("zetor123");
        return converter;
    }

    /**
     * resourceServerTokenServices 类的实例,用来实现令牌服务。
     *
     * @return
     */
    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(jwtTokenStore());
        return defaultTokenServices;
    }
}
  • Client Main 启动调用

  • 注册OAuth2RestTemplate对象

    @Slf4j
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @SpringBootApplication
    @ServletComponentScan
    public class ClientApp implements CommandLineRunner {
        public static void main(String[] args) {
            SpringApplication.run(ClientApp.class, args);
        }
    
    
        @Bean
        public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
                                                     OAuth2ProtectedResourceDetails details) {
            return new OAuth2RestTemplate(details, oauth2ClientContext);
        }
    
        @Override
        public void run(String... strings) {
            log.info("=================================Application Startup Success=================================");
        }
    }

  • 首页controller(此处支持前后端分离)

  • 此处支持前后端分离、配置front_flag如:http://127.0.0.1:9527/, 即可重定向至前端首页。

    @RequestMapping("/")
    public String index(Authentication authentication, Model model) {
        OAuth2AuthenticationDetails detail = (OAuth2AuthenticationDetails) authentication.getDetails();
        log.info("【登录成功】username:{}, sessonId:{}, {}", authentication.getPrincipal(), detail.getSessionId(), detail.getTokenValue());
        if (front_flag) {
            return "redirect:" + front_url + PaasConstant.PRE_FIX + detail.getTokenValue();
        } else {
            model.addAttribute("token", detail.getTokenValue());
            return "index";
        }
    }

四、启动程序

1. 创建数据库,运行sql。

2. 启动程序. ServerApp -> ClientApp

3. 调用客户端

在浏览器地址栏输入:http://127.0.0.1:8081/client

统一跳转到认证服务器 http://127.0.0.1:9086,如图

用户名:admin   、密码:123456

登录成功,跳转 账套选择页面:

选择账套后,进入首页:

以上,登录成功。

注:如果使用前后端分离系统,请在配置中增加前端首页地址,如图

FRONT_URL: http://10.0.0.32:9527/#/

登录成功后,将token返回前端即可。


本文着重介绍了 “SSO Client端” 相关代码 及启动相关流程。

后续文章会介绍 服务端集成 RBAC权限管理系统” 相关内容。


喜欢的朋友请 “点赞收藏”,多谢支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值