java - 如何使用弹簧靴将角度前端与 oauth2 身份验证绑定
问题描述
尽管有很多主题,但我无法弄清楚如何使用弹簧靴对我的角度项目进行身份验证,所以我尝试发布我的设置。
到目前为止,我所有的身份验证都是由 spring boot 和 work 处理的
@Configuration
@EnableOAuth2Sso
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout().clearAuthentication(true)
.logoutSuccessUrl("/")
.permitAll();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
我开始了一个新的 Angular 项目并尝试将它与 angular-oauth2-oidc 绑定。
在 auth.config.js
import { AuthConfig } from 'angular-oauth2-oidc';
export const authConfig: AuthConfig = {
clientId: 'xxxxxx',
issuer: 'https://accounts.google.com/',
// loginUrl: 'http://localhost:8080',
redirectUri: window.location.origin + '/user.html',
scope: 'openid profile email',
tokenEndpoint: 'https://www.googleapis.com/oauth2/v3/token',
// strictDiscoveryDocumentValidation: false,
userinfoEndpoint: 'http://localhost:8080/user',
// disableAtHashCheck: true,
// nonceStateSeparator: ',',
// clearHashAfterLogin: false,
};
在 login.component.ts
import { Component, OnInit } from '@angular/core';
import { OAuthService, JwksValidationHandler } from 'angular-oauth2-oidc';
import { authConfig } from '../auth.config';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private oauthService: OAuthService) {
this.oauthService.configure(authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}
ngOnInit() {
this.oauthService.initImplicitFlow(encodeURIComponent('http://localhost8080/'));
}
}
我不明白必须如何在此配置中处理身份验证。
解决方案
注释@EnableOAuth2Sso
在 OAuth2 客户端中转换您的 Spring 应用程序
相反,在您的场景中,您希望您的应用程序是一个ResourceServer
所以您应该使用@EnableResourceServer
注释。
Spring 安全性应该这样配置:
@Configuration
@EnableWebSecurity
@EnableResourceServer
@PropertySource(value = { "classpath:application.properties" }, encoding = "UTF-8", ignoreResourceNotFound = false)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
private Environment env;
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/swagger-ui.html","/webjars/**","/swagger-resources/**", "/v2/**","/csrf")
.permitAll()
.antMatchers("/**")
.authenticated()
.and()
.cors()
.configurationSource(corsConfigurationSource())
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
@Override
public void configure(final ResourceServerSecurityConfigurer config) {
config
.tokenServices(tokenServices())
.resourceId("RES_ID");
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
@Bean
public TokenStore tokenStore()
{
JwkTokenStore result = new JwkTokenStore("JWTKS_URL", accessTokenConverter());
return result;
}
@Bean
public JwtAccessTokenConverter accessTokenConverter()
{
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setAccessTokenConverter(new DefaultAccessTokenConverter() {
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
final OAuth2Authentication auth = super.extractAuthentication(map);
auth.setDetails(map);
return auth;
}
});
return converter;
}
@Bean
public JwtClaimsSetVerifier jwtClaimsSetVerifier() {
return new DelegatingJwtClaimsSetVerifier(Arrays.asList(issuerClaimVerifier(), customJwtClaimVerifier()));
}
@Bean
public JwtClaimsSetVerifier issuerClaimVerifier() {
try {
return new IssuerClaimVerifier(new URL("ISSUER CLAIMS URL"));
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Bean
public JwtClaimsSetVerifier customJwtClaimVerifier() {
return new CustomClaimVerifier();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
boolean abilitaCors = new Boolean(env.getProperty("profile.manager.web.cors.enbaled"));
if( abilitaCors )
{
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
configuration.setExposedHeaders(Arrays.asList("X-Auth-Token","x-auth-token", "x-requested-with", "x-xsrf-token","Access-Control-Allow-Origin", "content-type"));
source.registerCorsConfiguration("/**", configuration);
}
return source;
}
}
在角度方面,我建议您使用 angulat-oauth2-oidc 插件https://github.com/manfredsteyer/angular-oauth2-oidc
推荐阅读
- typescript - VSCode 扩展:QuickPick 不显示搜索的所有结果
- python - 编程 types.GenericAlias 中的含义是什么?
- python - 如何选择数据数据框
- amazon-dynamodb-dax - 在 Rails 应用程序中使用 DAX
- reactjs - 在授权标头 django-rest-framework 中发送仅 http cookie
- typescript - TS2339: 属性 'showNewCustomerFields' 不存在于类型'{ newCustomer(owner: any): void; }'
- c# - NotEmptyValidationRule 控件防止输入浮点数
- macos - 如何从嵌套的 shell 脚本中抛出错误
- ansible - Ansible - 变量的双下划线
- qiskit - 如何在 qiskit 的 state_city 图中获取密度矩阵元素的数值