html页面授权码,spring boot 2.0 整合 oauth2 authorization code授权码模式
oauth2 authorization code 大致流程
用户打开客户端后,客户端要求用户给予授权。
用户同意给予客户端授权。
客户端使用授权得到的code,向认证服务器申请token令牌。
认证服务器对客户端进行认证以后,确认无误,同意发放令牌。
客户端请求资源时携带token令牌,向资源服务器申请获取资源。
资源服务器确认令牌无误,同意向客户端开放资源。
security oauth2 整合的核心配置类
授权认证服务配置 AuthorizationServerConfiguration
security 配置 SecurityConfiguration
工程结构目录
image.png
pom.xml
security_oauth2_authorization
0.0.1-SNAPSHOT
jar
security_oauth2_authorization
oauth2 authorization_code 授权模式
org.springframework.boot
spring-boot-starter-parent
2.0.2.RELEASE
UTF-8
UTF-8
1.8
1.0.9.RELEASE
0.9.0
Finchley.RC2
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-oauth2
org.springframework.cloud
spring-cloud-starter-security
org.springframework.security
spring-security-jwt
${security-jwt.version}
org.springframework.boot
spring-boot-starter-freemarker
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
授权认证服务配置类 AuthorizationServerConfiguration
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private MyUserDetailsService userDetailsService;
@Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String secret = passwordEncoder.encode("secret");
clients.inMemory() // 使用in-memory存储
.withClient("client") // client_id
.secret(secret) // client_secret
//.autoApprove(true) //如果为true 则不会跳转到授权页面,而是直接同意授权返回code
.authorizedGrantTypes("authorization_code","refresh_token") // 该client允许的授权类型
.scopes("app"); // 允许的授权范围
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService)
.accessTokenConverter(accessTokenConverter())
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); //支持GET POST 请求获取token;
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter() {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication().getName();
final Map additionalInformation = new HashMap();
additionalInformation.put("user_name", userName);
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
OAuth2AccessToken token = super.enhance(accessToken, authentication);
return token;
}
};
//converter.setSigningKey("bcrypt");
KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("kevin_key.jks"), "123456".toCharArray())
.getKeyPair("kevin_key");
converter.setKeyPair(keyPair);
return converter;
}
}
web 安全配置 WebSecurityConfig
@Order(10)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsFitService;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/","/oauth/**","/login","/health", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsFitService).passwordEncoder(passwordEncoder());
auth.parentAuthenticationManager(authenticationManagerBean());
}
@Bean
public PasswordEncoder passwordEncoder(){
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
url 注册配置 MvcConfig
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login"); //自定义的登陆页面
registry.addViewController("/oauth/confirm_access").setViewName("oauth_approval"); //自定义的授权页面
}
}
# security 登陆认证 MyUserDetailsService
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
if ("admin".equalsIgnoreCase(name)) {
User user = mockUser();
return user;
}
return null;
}
private User mockUser() {
Collection authorities = new HashSet<>();
authorities.add(new SimpleGrantedAuthority("admin"));
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String pwd = passwordEncoder.encode("123456");
User user = new User("admin",pwd,authorities);
return user;
}
}
自定义登陆页面 login.html
登陆
username
Password
登陆
自定义授权页面 oauth_approval.html
授权
你是否授权client_id=client访问你的受保护资源?
action="../oauth/authorize" method="post">
Approve
action="../oauth/authorize" method="post">
Deny
application.yml
server:
port: 18084
spring:
application:
name: oauth2-server # 应用名称
thymeleaf:
prefix: classpath:/templates/
logging:
level:
org.springframework.security: DEBUG
1. 访问oauth2 服务
client_id:第三方应用在授权服务器注册的 Id
response_type:固定值 code。
redirect_uri:授权服务器授权重定向哪儿的 URL。
scope:权限
state:随机字符串,可以省略
如果未登陆则出现登录页面,输入用户名:admin 密码:123456 登陆系统
image.png
2. 成功登陆后自动跳转到授权页面
image.png
3. 携带授权之后返回的code 获取token
image.png
这里的账号和密码 是我们注册的 client_id 和 client_secret
image.png
成功登陆后获取token
image.png
4.携带toekn 访问资源
demo地址:
html页面授权码,spring boot 2.0 整合 oauth2 authorization code授权码模式相关推荐
- Spring boot 2.0 with Oauth2 + Jwt
2019独角兽企业重金招聘Python工程师标准>>> Spring boot 2.0 with Oauth2 + Jwt 在这篇文章中: Netkiller Spring Clou ...
- spring boot 2.0 源码分析(二)
在上一章学习了spring boot 2.0启动的大概流程以后,今天我们来深挖一下SpringApplication实例变量的run函数. 先把这段run函数的代码贴出来: /*** Run the ...
- spring boot 2.0 源码分析(三)
通过上一章的源码分析,我们知道了spring boot里面的listeners到底是什么(META-INF/spring.factories定义的资源的实例),以及它是创建和启动的,今天我们继续深入分 ...
- Spring Boot 2.0系列文章(四):Spring Boot 2.0 源码阅读环境搭建
前提 前几天面试的时候,被问过 Spring Boot 的自动配置源码怎么实现的,没看过源码的我只能投降��了. 这不,赶紧来补补了,所以才有了这篇文章的出现,Spring Boot 2. 0 源码阅 ...
- 【译】Spring Boot 2.0 官方迁移指南
前提 希望本文档将帮助您把应用程序迁移到 Spring Boot 2.0. 在你开始之前 首先,Spring Boot 2.0 需要 Java 8 或更高版本.不再支持 Java 6 和 7 了. 在 ...
- Spring Boot 2.0 迁移指南
点击上方"朱小厮的博客",选择"设为星标" 回复"666"获取新整理的1000+GB资料 前提 本文档将帮助您把应用程序迁移到 Spring ...
- Spring Boot 3.0.0-M1 Reference Documentation(Spring Boot中文参考文档) 9-16
9. 数据 Spring Boot与多个数据技术集成,包括SQL和NoSQL. 9.1. SQL数据库 Spring Framework提供扩展支持用于与SQL数据工作,从使用JdbcTemplate ...
- Spring Boot 2.0官方文档之 Actuator
https://blog.csdn.net/alinyua/article/details/80009435 前言:本文翻译自Spring Boot 2.0.1.RELEASE官方文档,该Spring ...
- Spring Boot 2.0(二):Spring Boot 2.0尝鲜-动态 Banner
Spring Boot 2.0 提供了很多新特性,其中就有一个小彩蛋:动态 Banner,今天我们就先拿这个来尝尝鲜. 配置依赖 使用 Spring Boot 2.0 首先需要将项目依赖包替换为刚刚发 ...
最新文章
- 在python中使用json格式存储数据
- 这个重量级产业,中国正在爆发!
- 第19章 归档模式下的数据库恢复
- 【牛客 - 370B】Rinne Loves Graph(分层图最短路 或 最短路dp)
- 阿里内推算法岗位编程笔试题
- PTA-6-3 使用函数的选择法排序 (25分)(C语言)
- mysqli 语句和mysql语句一样吗_如何为动态sql语句准备mysqli语句
- controller 中@autowired 报错_Spring中常用注解
- 一支python教学_第一只python爬虫
- android asset jar,android离线打包 可以使用,但总是报错 android_asset/null
- 如何编辑SDE数据(转自ESRI中国社区)
- Android APP渗透测试方法大全(百度云分享)
- 基于机器视觉技术的表面缺陷检测技术综述
- Windows蓝屏代码及解决方案最全合集
- 嵌入Circle映射和逐维小孔成像反向学习的鲸鱼优化算法-附代码
- SQLite3使用详解之二
- Required request body is missing 问题解决
- ESP32编译运行ADF音频库
- hdu多校第七场 1011 (hdu6656) Kejin Player 概率dp
- 在ICT求学时最大的痕迹
热门文章
- linux /proc 详解
- 点云平面提取_基于LiDAR点云数据滤波方法
- excel文件导入hive乱码_将excel中的数据导入hive
- 打不开磁盘配额linux,九度OJ 1455 珍惜现在,感恩生活 -- 动态规划(背包问题)...
- Python二级笔记(9)
- oracle中exists连接两个表,IN、EXISTS、多表连接,哪个速度更快
- thrift linux java,Apache Thrift环境配置
- Pytorch离线安装 matlibplot
- [转]Install Windows Server 2012 in VMware Workstation
- ajax 同步加载数据