在Azure AD身份验证Spring启动应用程序后手动分配角色



我有一个在Azure AD注册的应用程序,oauth2AllowImplicitFlow设置为True。

由于Azure AD的限制,我无法将用户角色和组添加到注册的应用程序中。这些将在将来从其他来源同步。同时,我需要一种在用户通过身份验证后从数据库或属性文件授权用户的方法。

这是我的基本设置,它通过了身份验证,但由于访问被拒绝而抛出服务器错误。

身份验证使用依赖项azure active directory spring-boot-start和spring-bot-starter-oauth2-client

spring.security.oauth2.client.registration.azure.client-id=xxxx
spring.security.oauth2.client.registration.azure.client-secret=yyyy
azure.activedirectory.tenant-id=zzzz
azure.activedirectory.user-group.allowed-groups=group1, group2, group3
spring.security.oauth2.client.registration.azure.provider=azure

组1、组2、组3存在,但为空,没有附加任何角色。

@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
@Autowired
private UserDetailsServiceImpl userDetailsServiceImpl;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService);
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceImpl);
}
}

我需要一种方法来拦截身份验证后的安全配置,并手动添加角色。我已经尝试扩展OidcUserService并将其插入AuthenticationManagerBuilder

@Component
public class UserDetailsServiceImpl extends OidcUserService {
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser;
Set<GrantedAuthority> grantedAuthorities = null; //TODO: GRANT ROLES
oidcUser = new DefaultOidcUser(grantedAuthorities, userRequest.getIdToken());
return oidcUser;
}
}

还有使用UserDetailsService实现的其他示例。我也试过了,但似乎都不起作用。

在用户通过Azure AD进行身份验证后,如何拦截spring安全性,并为经过身份验证的用户注入一些自定义角色。我知道,这样做的方法是使用Graph API授权用户,但目前,由于Azure AD的公司限制,没有在那里设置角色

您可以使用这样的东西:

.oauth2Login()
.userInfoEndpoint()
.userAuthoritiesMapper(this.userAuthoritiesMapper())
...
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
//fill in your authorities
return mappedAuthorities;
};
}

在您的SecurityConfig:中

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.anyRequest().authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService)
.and()
.addFilterAfter(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

然后您可以通过以下方式创建CustomAuthenticationFilter:

public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

最新更新