[英]Authenticating With Azure Directory and Fetch the Valid User Roles From Database
我必須為需要進行身份驗證的組織設計一個應用程序,使用 Spring Boot 將 SSO 與 Azure 目錄結合使用。
所有員工信息都存儲在 AD 中。 我的自定義應用程序將擁有自己的用戶和他們保存在數據庫中的角色。 並非組織中的每個員工都可以訪問此應用程序。 管理員將在數據庫(Mysql)中添加用戶及其角色。
通過在屬性文件中添加相關詳細信息並配置 WebSecurify Config 類,我能夠弄清楚使用 AD 進行 SSO
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
@Autowired
private AADAuthenticationFilter aadAuthFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS,
"/**").permitAll().anyRequest().authenticated()
.and()
.oauth2Login()
.userInfoEndpoint()
.oidcUserService(oidcUserService);
http
.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
http
.headers()
.frameOptions().sameOrigin()
.cacheControl();
http
.csrf().disable()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS,
"/**").permitAll().anyRequest().authenticated()
}
}
用戶通過驗證后,作為響應,我將獲得 JWT 令牌,我將使用該令牌用於所有進一步的 API 請求。 但問題是,我允許所有員工訪問該應用程序,因為他已使用 AD 進行身份驗證。 但是,一旦用戶通過身份驗證,我想檢查用戶是否在數據庫中可用,如果他不可用,我需要發送無效用戶,如果他是我的應用程序的有效用戶,我需要獲取角色並將其發送到前端作為有效響應。
我也想為用戶做服務級別的授權,我的大部分服務都使用了@PreAuthorize Annotation。 @PreAuthorize("hasRole('ROLE_VIEWER') 或 hasRole('ROLE_EDITOR')")
編輯 1
public class UserDetailsServiceImpl extends OidcUserService implements
CustomUserDetailsService {
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws
OAuth2AuthenticationException {
OidcUser oidcUser;
String mail=userRequest.getClientRegistration().getRegistrationId();
Set<GrantedAuthority> grantedAuthorities = getAuthorities(mail);
oidcUser = new DefaultOidcUser(grantedAuthorities,
userRequest.getIdToken());
return oidcUser;
}
private Set<GrantedAuthority> getAuthorities(String email) {
List<RoleIdDetails>
roleIdDetails=usersRepository.getRoleIdDeatils(email);
final Set<GrantedAuthority> authorities =
roleIdDetails.stream().map(role -> new SimpleGrantedAuthority("ROLE_" +
role.getRoleName().toString().toUpperCase())).collect(Collectors.toSet());
return authorities;
}
}
我已經使用我自己的自定義 OidcUserService 進行了更新,但仍然無法設置角色。
根據我的理解,您不需要使用 Mysql 數據庫來存儲用戶及其角色,我們只需通過 Azure Active Directory 即可實現此要求。
首先,我們可以在 Azure Active Directory 中創建一個組,方法是在 azure 門戶上單擊“組”->“新建組”按鈕,然后從 azure 廣告中的員工中選擇要加入該組的成員(如下圖所示) :
然后通過單擊“應用注冊”轉到您在 azure 廣告中的應用程序,然后單擊“清單”按鈕。
您還可以在上面屏幕截圖中的“appRoles”屬性下添加更多角色。
之后,在 azure ad 中的應用程序中,請單擊“本地目錄中的托管應用程序”。
現在您可以通過您在問題中提到的注釋(@PreAuthorize)為用戶進行服務級別授權,您也可以參考本教程。
順便說一句,如果我們想在 azure ad 中為組分配角色,我們需要為 azure ad( Azure Active Directory 定價)提供 Premium P1 或 P2 計划。 如果您沒有高級計划,您可以只為每個用戶分配一個角色,而不是最后一個屏幕截圖中的組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.