spring security实现authorization code模式# 系列文章目录

SpringSecurity实现OAuth2 JWT和OAuth2在SpringBoot下的实现

spring security实现authorization code模式

摘要自定义登录页面自动授权自定义密码验证跳转登录页面http转https放出refresh token的endpoint

摘要

为了将老项目接口安全暴露给第三方,我采取了OAuth 2.0 authorization code技术给接口做了鉴权。以spring security authorization code模式,论述了OAuthServer程序中自定义资源的方法。在项目中采用自定义登录页面替换默认的login页面,来使样式UI与自己系统风格保持一致;采用设置自动授权,省去了登录成功后要点击approve二次确认;采用了自定义密码验证,对接老系统账号数据与老系统密码编码验证保持一致,相应client_secret密码编码替换;采用了跳转登录页面http转https,使登录页链接与服务器https环境一致。

自定义登录页面

自定义登录页面必须放到后端项目里,跟授权接口在一个域里。 如果这是你的登录页html resources/static/login.html

需要在HttpSecurity方法里做相应配置

@Override

protected void configure(HttpSecurity http) throws Exception {

super.configure(http);

http

.formLogin().loginPage("/login.html")

.permitAll()

.and()

.csrf().disable()

;

}

在做如上配置后,spring security会自动映射默认的login接口为/login.html,登录页面的表单action也写为form action=“./login.html”。

自动授权

自动授权是在oauth_client_details表里autoapprove配置的。配置之后登录页数据账号密码验证成功就直接跳转到redirect_uri?code=xxxx。

自定义密码验证

先实现PasswordEncoder接口。 在实现并使用了自己实现的PasswordEncoder之后,client_secret也要用这种编码方式写入数据库。

public class CustomPasswordEncoder implements PasswordEncoder {

private static Logger log = LoggerFactory.getLogger(CustomPasswordEncoder.class);

@Override

public String encode(CharSequence rawPassword) {

return EncryptUtil.encodePassword(rawPassword.toString());

}

/**

rawPassword 数据来自表单输入;

encodedPassword 数据来自UserDetailsService#loadUserByUsername;

*/

@Override

public boolean matches(CharSequence rawPassword, String encodedPassword) {

if (encodedPassword == null || encodedPassword.length() == 0) {

log.warn("Empty encoded password");

return false;

}

return encode(rawPassword).equals(encodedPassword);

}

}

在WebSecurityConfigurerAdapter中定义Encoder的bean就会使用。

@Bean

public PasswordEncoder passwordEncoder() {

return new CustomPasswordEncoder();

}

记得修改UserDetailsService#loadUserByUsername方法。

跳转登录页面http转https

这里以springboot的tomcat为例。

server:

tomcat:

redirect-context-root: true

remote-ip-header: x-forwarded-for

protocol-header-https-value: https

protocol-header: x-forwarded-proto

放出refresh token的endpoint

在AuthorizationServerConfigurerAdapter的继承类中配置:

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

// 设置令牌

endpoints.tokenStore(tokenStore())

.userDetailsService(userDetailsService); // 此配置是将refresh token放出来。

}

推荐阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: