分享spring-security+jwt+oauth2(二)

125 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情

image.png

oauth2

oauth2产生背景:多个商户请求生产端的开放接口,需要管理商户端。

1、申请一个appid和秘钥

appid==qq账户--终生无法改变

apppwd==可以修改==qq密码

2、appid和密码生成一个token

3、使用该token调用接口

4、token临时且唯一的(有效期2个小时 8个小时等)

token失效---刷新token

oauth2

授权协议,它允许软件应用代表(而不是充当)资源拥有者去访问资源拥有者的资源。应用向资源拥有者请求授权,然后取得令牌(token),并用它来访问资源,并且资源拥有者不用向应用提供用户名和密码等敏感数据。

应用场景:

第三方联合登录 比如QQ/微信联合登录

开放接口 蚂蚁金服/腾讯开放接口

1、生成微信公众号授权链接。

image.png 2、当我们点击确认授权,会重定向跳转到redirect_url:http://127.0.0.1:2000?code=授权码

3、根据该授权码 获取accesstoken---2小时有效,授权码只能使用一次。

openid---用户关注该公众号的唯一id,关注后不会发生变化

image.png 4、调用微信接口根据accesstoken+openid获取用户基本信息

springSecurity整合oauth2.0

授权码类型:

1、需要提供appid和秘钥(读db加载)

2、配置回调地址

3、根据获取到的授权码获取accesstoken,验证accesstoken接口。

客户端想要调用接口,需要从服务端传递appid和app秘钥获取授权码,再根据授权码获取到accesstoken,根据accesstoken调用接口

整合代码

maven依赖(oauth)

配置类

@Component

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Bean

public PasswordEncoder passwordEncoder() {

return new BCryptPasswordEncoder();

}



/**

* 需要填写 认证账户 lijianb

* @param auth

* @throws Exception

*/

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.

inMemoryAuthentication()

.withUser("lijianb")

.password(passwordEncoder().encode("lijianb"))

.authorities("/*");

}



@Override

protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

.anyRequest().authenticated() //所有请求都需要通过认证

.and()

.httpBasic() //Basic登录

.and()

.csrf().disable(); //关跨域保护

}

}

/**
* 认证授权Server端
*/

@Component

@EnableAuthorizationServer

public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

@Autowired

private PasswordEncoder passwordEncoder;



@Override

public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

//允许表单提交

security.allowFormAuthenticationForClients()

.checkTokenAccess("permitAll()");

}



/**
* appid lijianb secret= 123456
* @param clients
* @throws Exception
*/

@Override

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.inMemory()

// appid

.withClient("lijiab")

// appsecret  获取accesstoken的用户和密码

.secret(passwordEncoder.encode("123456"))

// 授权码

.authorizedGrantTypes("authorization_code")

// 作用域

.scopes("all")

// 资源的id

.resourceIds("lijiab_resource")

// 回调地址

.redirectUris("http://www.lijiab.com/callback");

    }

}