为Azure AD身份验证的Spring Boot应用程序手动分配角色。

huangapple go评论115阅读模式
英文:

Assign roles manually after Azure AD authentication Spring boot app

问题

以下是您要翻译的内容:

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

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

以下是我的基本设置,可以通过身份验证,但由于访问被拒绝而产生服务器错误。

身份验证正常工作,使用了azure-active-directory-spring-boot-starter和spring-boot-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

group1、group2和group3存在,但是为空,没有附加任何角色。

@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 Security的方法是什么?并向经过身份验证的用户注入一些自定义角色。
我知道,使用Graph API授权用户的方式可以实现此目的,但目前由于Azure AD的公司限制,无法在那里设置角色。

英文:

I have an app registered at Azure AD, with oauth2AllowImplicitFlow set as True.

Because of restriction at Azure AD , I am no able to add user roles and groups to the registered application. These will be synchronized from other sources in future. Meanwhile, I need a way to authorize users from database or a property file after they are authenticated.

Here is my basic the setup that passes the authentication but spits out server error because of access denied.

Authentication is working with dependencies azure-active-directory-spring-boot-starter and spring-boot-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

group1, group2, group3 exists but are empty and have no roles attached.

@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);
    }
}

I need a way to intercept the security configuration after authentication, and add roles manually.
I have tried extending OidcUserService and plugging that into 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;
    }
}

There are other examples where an implementation of UserDetailsService is used. I tried that too, but none seems to be working.

What is the way to intercept the spring security after the user is authenticated via Azure AD, and inject some custom roles to the authenticated user.
I understand, this way to do this is authorize users using Graph API, but at this moment, due to company restrictions at Azure AD, setting up roles there is not happening.

答案1

得分: 1

你可以使用类似这样的代码:

.oauth2Login()
    .userInfoEndpoint()
        .userAuthoritiesMapper(this.userAuthoritiesMapper())
        ...
        
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
    return (authorities) -> {
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
        // 填写您的权限
        return mappedAuthorities;
    };
}
英文:

You can use something like this:

.oauth2Login()
	.userInfoEndpoint()
		.userAuthoritiesMapper(this.userAuthoritiesMapper())
		 ...

private GrantedAuthoritiesMapper userAuthoritiesMapper() {
		return (authorities) -&gt; {
			Set&lt;GrantedAuthority&gt; mappedAuthorities = new HashSet&lt;&gt;();
            //fill in your authorities
            return mappedAuthorities;
        };
}

答案2

得分: 0

在你的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 {

英文:

In your SecurityConfig:

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

Then you can create the CustomAuthenticationFilter by :

public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

huangapple
  • 本文由 发表于 2020年9月11日 16:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63843597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定