SpringSecurity(7)--- Security+JWT搭建简单的授权服务器和资源服务器

Security+JWT搭建简单的授权服务器和资源服务器

之前有两篇博客分别将来介绍了 OAuth 2.0JWT

1、OAuth 2.0详解

2、SpringSceurity(6)---JWT详解

这边通过Security+JWT搭建简单的授权服务器和资源服务器示例。

整体流程大概是这样的

JWT 认证流程

1、用户先访问授权服务器。传入用户输入用户名/密码登录,授权服务器认证成功后,会返回给客户端一个 JWT
2、用户在访问资源服务器。当用户希望访问一个受保护的路由或者资源的时候,需要请求头的 Authorization 字段中使用Bearer 模式添加 JWT,其内容看起来是下面这样
   Authorization: Bearer复制代码
3、资源服务器保护路由将会检查请求头 Authorization 中的 JWT 信息,如果合法,则允许用户的行为

下面开始搭建

一、搭建授权服务器

授权服务器配置类

/**
 * @Description: 授权服务器配置
 *   使用 @EnableAuthorizationServer 来配置授权服务机制,并继承 AuthorizationServerConfigurerAdapter 该类重写 configure 方法定义授权服务器策略
 */
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 使用同一个密钥来编码 JWT 中的  OAuth2 令牌,在资源服务器解析JWT的时候需要有一样的密钥
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("dada");
        return converter;
    }

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

    /**
     * 告诉Spring Security Token的生成方式
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .authenticationManager(authenticationManager)
            .tokenStore(jwtTokenStore())
            .accessTokenConverter(accessTokenConverter());
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //添加客户端信息 使用in-memory存储客户端信息
        clients.inMemory()
                //客户端标识 ID
            .withClient("clientId")
                //客户密钥
            .secret("666666")
                //客户端访问范围,默认为空则拥有全部范围
            .scopes("read_userinfo")
                //客户端使用的授权类型,默认为空
            .authorizedGrantTypes(
                "password",
                "authorization_code",
                "refresh_token");
    }
}

application.properties配置类

security.user.name=xuxiaoxiao
security.user.password=123456

这里设置 用户名为: xuxiaoxiao 密码为: 123456 端口号默认为: 8080

说明 有关其它代码这里就不再贴出,最后会给出整个demo的github地址。


二、搭建资源服务器

资源服务器配置类

/**
 * @Description: 资源服务器通过 @EnableResourceServer 注解来开启一个 OAuth2AuthenticationProcessingFilter 类型的过滤器
 * 通过继承 ResourceServerConfigurerAdapter 类来配置资源服务器
 */
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated().and()
            .requestMatchers().antMatchers("/api/**");
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 与授权服务器使用共同的密钥进行解析
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("dada");
        return converter;
    }
}

UserController

@Controller
public class UserController {

    @RequestMapping("/api/userinfo")
    public ResponseEntity<String> getUerInfo() {
        //这里会做解析jwt操作,获取jwt中的用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return ResponseEntity.ok(username);
    }

}

application.properties

server.port=8081

这里只是配置端口号为 8081


三、测试

1、整体测试流程

1.)启动jwt-authserver(授权服务器),端口8080

2.) 启动jwt-resourceserver(资源服务器),端口8081

3.) 请求授权服务器,获取jwt令牌

curl -X POST --user clientId:666666 http://localhost:8080/oauth/token -H "accept: application/json" -H "content-type: application/x-www-formurlencoded" 
-d "grant_type=password&username=xuxiaoxiao&password=123456&scope=read_userinfo"

4.) 带上jwt令牌请求资源服务器

curl -X GET http://localhost:8081/api/userinfo -H "authorization: Bearer 上面返回的jwt令牌

2、postman测试

先请求授权服务器

从请求中可以看出,授权服务器已经成功返回 access_token

再请求资源服务器

因为上面授权服务器已经返回access_token,那么我们在请求资源服务器的时候,就可以在请求头中加入这个token。

可以看出资源服务器已经成功解析这个access_token,获取到当前用户名。

总结:这个demo实现了基于Security+JWT搭建简单的授权服务器和资源服务器,也仅仅是搭建了简单的demo。里面的数据都是写死的并没有通过配置走,对于配置类也没有做详细的说明。

Github地址 : 基于Security+JWT搭建简单的授权服务器和资源服务器


参考

1、授权服务器支持 JWT 令牌 (杨波)

2、oauth2-demo(demo更加完整)

3、Spring Security 与 OAuth2


别人骂我胖,我会生气,因为我心里承认了我胖。别人说我矮,我就会觉得好笑,因为我心里知道我不可能矮。这就是我们为什么会对别人的攻击生气。
攻我盾者,乃我内心之矛(25)
posted on 2020-07-27 21:54  雨点的名字  阅读(2021)  评论(2编辑  收藏  举报