SpringSecurity + Oauth2的配置和使用

如何使用SpringSecurity和Oauth2去实现一个安全配置(四大模式之授权码模式)?

1.导入依赖

<dependency>
                  <groupId>org.springframework.security.oauth</groupId>
                 <artifactId>spring-security-oauth2</artifactId>
			   <version>2.3.6.RELEASE</version>
             </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

2.配置类

//SpringSecurity的配置类 放行/oauth/,后续需要获取token 必须开启
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/oauth/**","/login/**")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll();
    }
//授权服务器的配置
 @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //配置客户端信息
        clients.inMemory()
                .withClient("user")
                .secret(passwordEncoder.encode("123123"))
                .accessTokenValiditySeconds(3600)
                //授权成功后跳转的地址,后面携带授权码
                .redirectUris("http://www.baidu.com")
                //授权范围
                .scopes("all")
                //授权类型,授权码
                .authorizedGrantTypes("authorization_code");
    }
//资源服务器配置
@Configuration
@EnableResourceServer
public class ResouceServer extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest()
                .authenticated()
                .and()
                .requestMatchers()
                //配置了以下路径之后,只有携带token才可以访问
                .antMatchers("/user/**","/test/**");
    }
}

3.获取授权码

http://localhost:8080/oauth/authorize?response_type=code&client_id=user&current_uri=http://www.baidu.com

发送以上请求之后先会跳到springsecurity的登录界面,登录之后就会执行以上请求,成功后跳转到http://www.baidu.com?code=授权码

4.获取token

可以使用postman工具去发送请求http://localhost:8080/oauth/token,请求方式设为post,把Authorization的Type设为Basic Auth 右侧填写客户端用户名和密码 ,Body里面添加 以下键值对:
key value
grant_type authorization_code
code 第三步生成的授权码
client_id user
redirect_uri http://www.baidu.com

点击发送 ,就会生成一个token

5.到资源服务器下获取资源

去资源服务器配置类中配置的路径下,携带token 发送请求即可获取到相应的用户资源。这样App就能获取到qq的一些用户信息拿去登录了 。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值