我从互联网上获得了一些代码 这是它:
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
CustomerBean customerBean = customerService.getCustomerBeanByEmail(userName);
if (customerBean == null) {
throw new UsernameNotFoundException("Invalid username or password");
} else if(!CustomerStatus.ACTIVATED.equals(customerBean.getStatus())) {
throw new LockedException("User account is locked");
}
return createCustomer(customerBean);
}
public void signIn(CustomerBean customer) {
SecurityContextHolder.getContext().setAuthentication(authenticate(customer));
}
private Authentication authenticate(CustomerBean customerBean) {
return new UsernamePasswordAuthenticationToken(createCustomer(customerBean), customerBean.getPassword(), createAuthority());
}
private User createCustomer(CustomerBean customerBean) {
return new CustomerDetailsImpl(customerBean, createAuthority());
}
private Set<GrantedAuthority> createAuthority() {
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
return grantedAuthorities;
}
and my Configure method
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customerDetailsServiceImpl).passwordEncoder(new ShaPasswordEncoder(256));
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/403").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.failureUrl("/loginError")
.defaultSuccessUrl("/app/home", true)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logoutUser")
.permitAll()
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf().disable();
}
我的问题是:如何将角色添加到特定网址?
像has_user,has_admin在代码中添加什么?
答案 0 :(得分:1)
您可以在 configure(HttpSecurity http)开头的authorizeRequests部分添加特定网址所需的角色,例如
.antMatchers("/your/user/**").hasRole("user")
.antMatchers("/your/admin/url").hasRole("admin")