SSO 单点登陆

单点登录,英文是 Single Sign On(缩写为 SSO)。即多个站点共用一台认证授权服务器,用户在站点登录后,可以免登录访问其他所有站点

CAS 是 Central Authentication Service 的缩写 —— 中央认证服务,一种独立开放指令协议,是 Yale 大学发起的一个企业级开源项目,旨在为 Web 应用系统提供一种可靠的 SSO 解决方案。

SSO是一种思想,而CAS只是实现这种思想的一种框架而已

CAS支持oauth2 协议

SSO是一种思想,或者说是一种解决方案,是抽象的,我们要做的就是按照它的这种思想去实现它

OAuth2是用来允许用户授权第三方应用访问他在另一个服务器上的资源的一种协议,它不是用来做单点登录的,但我们可以利用它来实现单点登录。

一.Oauth

1.介绍

OAuth2是目前最流行的授权机制,用来授权第三方应用,获取用户数据。允许用户授权B应用不提供帐号密码的方式去访问该用户在A应用服务器上的某些特定资源。

2.oauth 四个角色

resource owner:资源所有者,这里可以理解为用户。

client:客户端,可以理解为一个第三方的应用程序 即微博 CSDN。

resource server:资源服务器,它存储用户或其它资源。

authorization server:认证/授权服务器,它认证resource owner的身份,为 resource owner提供授权审批流程,并最终颁发授权令牌(Access Token)。

3.四种授权模式

* authorization_code 授权码模式

* password 密码模式

* client_credentials 客户端模式

* implicit 简单模式

目的:颁发token

refresh_token 这个不是一种模式 是支持刷新令牌的意思

4.四种模式测试

所有授权端点(EndterPoints),意思就是授权微服务启动后 可以访问哪些路径

认证服务器的ip以及端口号 localhost:8500

localhost:8500/oauth/token

常用路径

路径

说明

/oauth/authoriz

授权端点

/oauth/token

令牌端点 获取token

/oauth/confirm_access

用户确认授权提交端点

/oauth/error

授权服务错误信息端点

/oauth/check_token

用于资源服务访问的令牌解析端点

/oauth/token_key

提供公有密匙的端点,如果你使用JWT(RSA)令牌的

5.搭建认证服务器

5.1启动nacos
5.2创建授权微服务
5.3加入依赖
<!--点带登陆oauth-->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.5.RELEASE</version>
        </dependency>
<!--服务之间的调用-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
5.4授权码模式
5.4.1配置核心的配置文件

授权的配置信息需要继承AuthorizationServerConfigurerAdapter

将授权的客户端的信息保存到内存里面

package com.aaa.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

import javax.annotation.Resource;

@Configuration
@EnableAuthorizationServer // 认证配置
public class MuOauthConfig extends AuthorizationServerConfigurerAdapter {
@Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    //四个角色

    /**
     * 客户端 第三方信息 数据库 内存
     * 用户
     * 认证服务器
     * 资源服务器
     * @param
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin")//第三方客户端的用户名
                .secret(bCryptPasswordEncoder.encode("123456"))//密码
                .scopes("all")//授权的范围
                .authorities("all")//授权的资源
                .autoApprove(true)//是否是自动授权
                .authorizedGrantTypes("authorization_code")//授权码模式
                .redirectUris("https://www.baidu.com");//授权的路径 能访问的都可以
    }
}

在启动类写密码的编码

5.4.2配置springsecurity的配置信息
package com.aaa.config;

import com.aaa.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().permitAll();
        http.authorizeRequests().antMatchers("userlogin","/oauth/**").permitAll();

        http.authorizeRequests().anyRequest().authenticated();// 除去不需要认证的路径的其它路径都需要认证

        http.csrf().disable();// 关闭csrf的保护
        http.cors();//可以跨域
    }
    private void extracted(HttpServletResponse response, Result result) throws IOException {

        response.setContentType("application/json;charset=utf8");
        ObjectMapper objectMapper = new ObjectMapper();
        //使用ObjectMapper将result转化成json字符串
        String s = objectMapper.writeValueAsString(result);
        //响应json数据
        PrintWriter writer = response.getWriter();
        writer.println(s);
        writer.flush();//刷新
        writer.close();//关闭
    }
@Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    // 自定义用户的信息
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("pxy")
                .password(bCryptPasswordEncoder.encode("123456"))
                .roles("ADMIN");
    }
}
5.4.3申请授权码:

http://localhost:8081/oauth/authorize?response_type=code&client_id=admin&scop=all

授权码:vPMEDk

5.4.4 根据授权码生成token

localhost:8081/oauth/token?grant_type=authorization_code&code=4WXzET&client_id=admin&redirect_url=http://www.baidu.com&scope=all

因为是post的请求浏览器请求不了需要借助第三方的调式工具

token: bd592910-1244-4d8a-bfb4-5b1f0004cdee

5.5简单模式

修改一下模式

其他地方保持不变

访问地址:

localhost:8081/oauth/authorize?response_type=token&client_id=admin&scope=all

登陆之后可以在浏览器获取

5.6客户端模式

5.7密码模式

安全配置


    @Resource
    private AuthenticationManager authenticationManager;


//配置凭证信息
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }


    //安全配置
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .checkTokenAccess("permitAll()")// 校验token 放行
                .tokenKeyAccess("permitAll()");//获取token的值
    }

有安全配置就不需要认证了

6.校验token

6.1生成所需要的token

加入jar包

<!--security使用的jwt-->

<dependency>

<groupId>org.springframework.security</groupId>

<artifactId>spring-security-jwt</artifactId>

<version>1.1.0.RELEASE</version>

</dependency>

配置

    //配置凭证信息
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .tokenStore(getTokenStore())//token 存储的地方
                .accessTokenConverter(jwtAccessTokenConverter());//生成token的bean 解析token的bean
    }
    /**
     * 生成token的bean
     * 解析token的bean
     */
    @Bean
    public TokenStore getTokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("pxy");
        return jwtAccessTokenConverter;
    }

7.获取使用token

 http.formLogin().loginProcessingUrl("/userlogin")
                        .successHandler((httpServletRequest, httpServletResponse, authentication) -> {

                            String username = httpServletRequest.getParameter("username");
                            String password = httpServletRequest.getParameter("password");

                            // hutool 工具 发出post请求 获取token的值
                            HttpRequest post = HttpUtil.createPost("http://localhost:8081/oauth/token");
                            //参数
                            post.form("grant_type","password");
                            post.form("client_id","admin");
                            post.form("client_secret","123456");
                            post.form("username",username);
                            post.form("password",password);

                            HttpResponse execute = post.execute();//发送请求
                            String body = execute.body();
                            System.out.println(body);
                            //

                            extracted(httpServletResponse,new Result(200, "登陆成功", body));

                        });

因为是字符串所以要转换成json

//token的值
//字符串转换成map
JSONObject entries = JSONUtil.parseObj(body);
Object o = entries.get("access_token");

8.资源服务器

加jar包

<dependency>

<groupId>org.springframework.security.oauth</groupId>

<artifactId>spring-security-oauth2</artifactId>

<version>2.3.5.RELEASE</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure -->

<dependency>

<groupId>org.springframework.security.oauth.boot</groupId>

<artifactId>spring-security-oauth2-autoconfigure</artifactId>

<version>2.3.5.RELEASE</version>

</dependency>

写配置文件

package com.aaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(jsr250Enabled = true,prePostEnabled = true,securedEnabled = true)
public class MyResConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                //.access("@RbacConfig.hasPermission(request,authentication)")
                .and()
                .csrf().disable();
    }
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("pxy");
        return jwtAccessTokenConverter;
    }
}

测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值