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授权码模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java calendar_Java C
- 下一篇: this.getstate_Java线程