Spring Security OAuth 2.0


简介

Spring Cloud Security Oauth2(SpringBoot版本的集成过于麻烦)就是将 OAuth 2.0 和 Spring Security 集成在一起,得到一套完整的安全解决方案,可以实现单点登录、令牌中继、令牌交换等功能。

在 OAuth 2.0中,provider 角色事实上是把授权服务和资源服务分开,有时候它们也可能在同一个应用中,用 Spring Security OAuth 你可以选择把它们分成两个应用,当然多个资源服务可以共享同一个授权服务。获取 token 的请求由 Spring MVC 的控制端点处理,访问受保护的资源由标准的 Spring Security 请求过滤器处理。

使用

环境搭建

1、引入依赖


    org.springframework.cloud
    spring-cloud-starter-oauth2


    org.springframework.cloud
    spring-cloud-starter-security


    org.springframework.boot
    spring-boot-starter-web


2、Spring Security 配置

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 强散列哈希加密实现
     * @return BCryptPasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     * @return authenticationManagerBean
     * @throws Exception 异常信息
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 禁用csrf
                .cors().and().csrf().disable()
                // 过滤请求
                .authorizeRequests()
                // 放行oauth认证接口
                .antMatchers("/login.html", "/oauth/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证,用户登录后可访问
                .anyRequest().authenticated();
    }

}

自定义用户信息

@Service
public class UserService implements UserDetailsService {

    private List userList;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initData() {
        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
        userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
        userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client")));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(findUserList)) {
            return findUserList.get(0);
        } else {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
    }
}

配置认证服务器

@Configuration
// 开启认证服务器
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    /**
     * 使用密码模式需要配置
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                // 通过内存保存
                .inMemory()
                // 客户端Id
                .withClient("client")
                // 秘钥
                .secret("123456")
                // 配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                // 配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                // 配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                // 配置申请的权限范围
                .scopes("all")
                // 配置grant_type,表示授权类型,authorization_code:授权码模式,password:密码模式
                .authorizedGrantTypes("authorization_code", "password");
    }
}

配置资源服务器

@Configuration
// 开启资源服务器
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            // 拦截所有请求
            .authorizeRequests().anyRequest().authenticated().and()
            // 配置需要保护的资源路径
            .requestMatchers().antMatchers("/user/**");
    }
}

配置受保护资源

@RestController
public class UserController {

    @GetMapping("/user/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        // 返回自定义资源对象
        return authentication.getPrincipal();
    }

}

测试

授权码模式

启动服务后,在浏览器访问该地址进行登录授权,http://localhost:9401/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://www.baidu.com&scope=all&state=normal

输入账号面后进行登录操作,示意图如下:

登录后进行授权操作,示意图如下:

授权操作之后,浏览器会带着授权码跳转到我们指定的路径(redirect_rul):https://www.baidu.com/code=eTsADY&state=normal ,此地址中 code 的值就是授权码,使用授权码请求该地址获取访问令牌:http://localhost:9401/oauth/token ,请求时需要携带以下参数(可以通过Postman进行伪造)

  • grant_type:authorization_code,授权码模式

  • code:eTsADY,刚刚获取到的

  • client_id:client,认证服务器配置的

  • redirect_url:http://www.baidu.com ,认证后需要跳转的地址

  • scope:all,权限范围

接下来通过在请求头中添加访问令牌,访问需要登录认证的接口进行测试,发现已经可以成功访问:http://localhost:9401/user/getCurrentUser ,到此,授权码模式测试完成。


密码模式

使用密码请求该地址获取访问令牌:http://localhost:9401/oauth/token ,首先配置认证信息,其次将 grant_type 修改为 password,即可成功获取到需要认证的接口数据了。