Meine App ist eine vollständige Web-Anwendung RESTful-Stil, die nur JSON-Schnittstellen bietet (keine Web-Seiten). Ich möchte meine eigenen Controller schreiben, die ich voll und ganz den Login-Prozess steuern:Wie kann ich mich mit meinem eigenen Controller anmelden?
@GetMapping("/login")
public String login(@RequestParam String username,
@RequestParam String password,
HttpServletRequest req,
HttpServletResponse resp) {
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(username, password);
try {
Authentication auth = authManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (AuthenticationException ex) {
return ex.getMessage();
}
return "success";
Und das ist mein UserDetailsService
:
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
if (!name.equals("whf")) {
throw new UsernameNotFoundException("not found");
}
// load roles
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("admin"));
return new User("whf", "pwd", authorities);
}
}
Aber wenn ich die URL zugreifen, die admin
Rolle erfordert, habe ich Access is Denied
:
@GetMapping("/a")
@PreAuthorize("hasRole('admin')")
public String A(Principal principal) {
return "a";
}
Aktueller Benutzer hat die admin
Rolle erhalten. Warum kann ich nicht auf /a
zugreifen?