我正在使用spring登录功能创建登录名,但无法正常工作。我可以登录,但无法访问其他用户的URL身份验证。
public class Login {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int loginId;
private String username;
private String emailId;
private String mobileNumber;
private String password;@
OneToMany(mappedBy = "login", cascade = CascadeType.ALL, orphanRemoval = true) private List < Role > roles;
}
@Entity @Table
public class Role {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int roleId;
private String name;@
ManyToOne(fetch = FetchType.LAZY)@ JoinColumn(name = "login_id") private Login login;
}
public class MySimpleUrlAuthSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();@
Autowired LoginDAOImpl loginDAO;@
Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
String targetUrl = determineTargetUrl(request, response, authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
MyUserPrincipal user = (MyUserPrincipal) authentication.getPrincipal();
Login login = user.getLogin();
System.out.println("In url handler" + user.getAuthorities().toString());
if (login != null) {
if (login.getSchool() == null && login.getParent() == null && login.getTeacher() == null && login.getAccountant() == null && login.getStudent() == null) {
return "admin/adminhome";
} else if (login.getParent() != null) {
return "parent/parenthome";
} else if (login.getTeacher() != null) {
return "teacher/teacherhome";
} else if (login.getAccountant() != null) {
return "accountant/accountanthome";
} else {
return "school/schoolhome";
}
} else {
return "/login";
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
public class MyUserPrincipal extends User {
private Login login;
public MyUserPrincipal(Login login, Collection <? extends GrantedAuthority > authorities, int schoolId, School schoolDisplayData) {
super(login.getUsername(), login.getPassword(), authorities);
this.login = login;
}
public MyUserPrincipal(Login login, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection <? extends GrantedAuthority > authorities) {
super(login.getUsername(), login.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.login = login;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {@
Autowired LoginDAOImpl userRepository;@
Autowired SchoolServiceImpl schoolServiceImpl;@
Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
if (StringUtils.isEmpty(s)) {
throw new UsernameNotFoundException(s);
}
Login login = userRepository.getByEmailIdOrUsernameOrMobileNumber(s, s, s);
if (login == null) {
throw new UsernameNotFoundException(s);
}
List < UserAuthorities > grantedAuthorities = new ArrayList < > ();
for (Role role: login.getRoles()) {
grantedAuthorities.add(new UserAuthorities("ROLE_" + role.getName().toUpperCase(), login.getLoginId()));
}
return new MyUserPrincipal(login, true, true, true, true, grantedAuthorities);
}
}
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler() {
return new MySimpleUrlAuthSuccessHandler();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
/*--Permit all starts here--*/
/*Home page*/
.antMatchers(HttpMethod.GET, "/").permitAll()
.antMatchers(HttpMethod.GET, "/forgotPassword").permitAll()
/*Resources*/
.antMatchers("/css/**", "/images/**", "/js/**", "/scss/**", "/vendor/**").permitAll()
/*--Authenticated starts here--*/
.anyRequest().authenticated()
.antMatchers("/school/**").hasRole("SCHOOL")
.antMatchers("/accountant/**").hasRole("ACCOUNTANT")
.antMatchers("/parent/**").hasRole("PARENT")
.antMatchers("/teacher/**").hasRole("TEACHER")
.antMatchers("/admin/**").hasRole("ADMIN")
/*Login Flow*/
.and().formLogin()
.loginPage("/login")
.successHandler(myAuthenticationSuccessHandler())
.permitAll();
// http.authorizeRequests() // .antMatchers("/**").permitAll();
}
public SimpleUrlAuthenticationFailureHandler failureHandler() {
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
}
public static void main(String[] args) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
System.out.println(encoder.encode("11111"));
}
}