一、认证服务器
1.授权码模式
1.添加pom
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.配置核心配置文件
@Configuration
@EnableAuthorizationServer
public class MyOauthConfig extends AuthorizationServerConfigurerAdapter {
@Resource
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
// 客户端id
.withClient("admin")
// 客户端密码
.secret(bCryptPasswordEncoder.encode("123456"))
// 授权范围
.scopes("all")
// 是否自动授权
.autoApprove(true)
// 授权权限
.authorities("all")
// 重定向地址
.redirectUris("https://www.baidu.com/")
// 授权类型
.authorizedGrantTypes("authorization_code");
}
}
启动类的Bean
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
3.SpringSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().permitAll();
http.authorizeRequests().antMatchers("/userlogin", "/oauth/**").permitAll(); //代表放行
http.authorizeRequests().anyRequest().authenticated(); //出去上面放行路径,其他都需要验证
http.csrf().disable(); //关闭csrf 方便HTML文件通过
http.cors(); //可以跨域
}
@Resource
private BCryptPasswordEncoder passwordEncoder;
// 自定义用户的信息
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("ww")
.password(passwordEncoder.encode("123456"))
.roles("ADMIN");
}
public void printJsonData(HttpServletResponse response, Result result) {
try {
response.setContentType("application/json;charset=utf8"); // json格式 编码是中文
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(result);// 使用ObjectMapper将result转化json为字符串
PrintWriter writer = response.getWriter();
writer.print(s);
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2.申请授权码
http://localhost:8809/oauth/authorize?response_type=code&client_id=admin&scop=all
输入ww 密码 123456
3.生成Token
复制授权码
复制路径
localhost:8809/oauth/token?grant_type=authorization_code&code=5y3Hk0&client_id=admin&redirect_url=http://www.baidu.com&scope=all
到PostMan post方法,生成Token
2.简单模式
代码同上,将授权模式改为简单模式 implicit
访问地址
http://localhost:8809/oauth/authorize?response_type=token&client_id=admin&scope=all
3.客户端模式
代码同上,将授权模式改为简单模式 client_credentials
postman访问
localhost:8809/oauth/token?grant_type=client_credentials&client_id=admin&scope=all
4.密码模式
security的配置文件中进行的配置
//配置密码模式所需
@Bean
public AuthenticationManager getAuthManger() throws Exception {
return super.authenticationManagerBean();
}
oauth的配置文件中配置:
//配置凭证信息
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
不想重复输入第三方用户名和密码
// 安全配置
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients()
.checkTokenAccess("permitAll()")
.tokenKeyAccess("permitAll()");
}
5.验证Token
输入
localhost:8809/oauth/check_token?token=f15a6049-4cac-4ed9-93e9-dae31e62a95c
6.使用Jwt类型的token
//配置凭证信息
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(getTokenStore())//存放位置
.accessTokenConverter(jwtAccessTokenConverter());//生成token的bean
}
@Bean
public TokenStore getTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* 生成Token的bean
* 解析Token的bean
*/
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("ww");
return jwtAccessTokenConverter;
}
1.加jar
<!--security使用的jwt-->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
security
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginProcessingUrl("/userlogin")
.successHandler((httpServletRequest, httpServletResponse, authentication) -> {
String username = httpServletRequest.getParameter("username");
String password = httpServletRequest.getParameter("password");
// 获取Token
HttpRequest post = HttpUtil.createPost("http://localhost:8809/oauth/token");
post.form("grant_type", "password");
post.form("client_id", "admin");
post.form("client_secret", "123456");
post.form("username", "ww");
post.form("password", "123456");
HttpResponse execute = post.execute();
String body = execute.body();
System.out.println(body);
// 字符串值
// 转化为map
JSONObject entries = JSONUtil.parseObj(body);
Object o = entries.get("access_token");
printJsonData(httpServletResponse, new Result(200, "成功", o));
});
http.authorizeRequests().antMatchers("/userlogin", "/oauth/**").permitAll(); //代表放行
http.authorizeRequests().anyRequest().authenticated(); //出去上面放行路径,其他都需要验证
http.csrf().disable(); //关闭csrf 方便HTML文件通过
http.cors(); //可以跨域
}