@Component
public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
private static final AuthorizationDecision DENY = new AuthorizationDecision(false);
private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings;
@Autowired
private HandlerMappingIntrospector introspector;
public CustomAuthorizationManager(@Autowired MenuMapper menuRepository) {
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
mappings = new ArrayList<>();
//AndRequestMatcher
AuthorizationManager<RequestAuthorizationContext> requestAuthorizationContextAuthorizationManager = (context, variables) -> new AuthorizationDecision(true);
List<Menu> allMenus = menuRepository.findAll();
for (Menu menu : allMenus) {
List<Role> roles = menu.getRoles();
String[] roleArr = new String[roles.size()];
for (int i = 0; i < roleArr.length; i++) {
roleArr[i] = roles.get(i).getName();
}
RequestMatcher pattern = mvcMatcherBuilder.pattern(menu.getPattern());
if (roleArr.length == 0) {
mappings.add(new RequestMatcherEntry(pattern, requestAuthorizationContextAuthorizationManager));
}else{
mappings.add(new RequestMatcherEntry(pattern, AuthorityAuthorizationManager.hasAnyAuthority(roleArr)));
}
}
mappings.add(new RequestMatcherEntry(AnyRequestMatcher.INSTANCE, new AuthenticatedAuthorizationManager()));//其他登录才能访问
}
@Override
public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext request) {
Iterator var3 = this.mappings.iterator();
RequestMatcherEntry mapping;
RequestMatcher.MatchResult matchResult;
do {
if (!var3.hasNext()) {
return DENY;
}
mapping = (RequestMatcherEntry) var3.next();
RequestMatcher matcher = mapping.getRequestMatcher();
matchResult = matcher.matcher(request.getRequest());
} while (!matchResult.isMatch());
AuthorizationManager<RequestAuthorizationContext> manager = (AuthorizationManager) mapping.getEntry();
return manager.check(authentication, request);
}
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.userDetailsService(userDetailsService)
.httpBasic(withDefaults())
.authorizeHttpRequests((authorize) -> {
authorize
.anyRequest().access(authorizationManager);
}
)
.logout(logout -> logout
.logoutSuccessHandler(logoutSuccessHandler)//登录成功
.invalidateHttpSession(true)
)
.formLogin(formLogin -> formLogin
.successHandler(authenticationSuccessHandler)//登录成功
.failureHandler(authenticationFailureHandler)//登录失败
)
;
return http.build();
}