Reputation: 513
I know, this question are posted multiple times but all the answers dont help me, also i will post here my case.
My configuration of SpringBoot-Project looks like:
SecurityConfig
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/secure/**")
.authorizeRequests()
.anyRequest()
.hasRole(ERole.USER.name);
http.formLogin().loginPage("/auth").permitAll();
}
}
Enum with Roles
public enum ERole implements GrantedAuthority {
USER("USER");
public final String name;
ERole(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return this.name;
}
}
Custom Authentication
public class UserAuth implements Authentication {
// Implements all the methods ...
// getAuthorities() return the list of ERole
}
Auth REST Controller
@RestController
public class AuthRestCtrl {
public static final String PERMIT_URL = AuthCtrl.INDEX_URL + "/rest/permit";
private ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder();
/**
* Führt die Authentifizierung des Nutzers durch
*/
@RequestMapping(value = "/auth/rest/permit", method = RequestMethod.POST)
public boolean permitUser(@RequestBody AuthData authData) {
Account account = new Account();
account.setLogin("test");
account.setSalt("");
account.setPassword(this.shaPasswordEncoder.encodePassword("123456", account.getSalt()));
account.addRole(ERole.USER);
User user = new User();
user.setName("...");
user.setSurname("...");
user.setAccount(account);
if (!authData.getUsername().equals(account.getLogin())) {
return false;
}
if (!this.shaPasswordEncoder.isPasswordValid(account.getPassword(), authData.getPassword(), account.getSalt())) {
return false;
}
UserAuth userAuth = new UserAuth(user);
userAuth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(userAuth);
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
attr.getRequest().getSession(true).setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
return true;
}
Now if i redirect (via javascript after my restclient returns true) to any secure page "/secure/home" i get status 403. I read that status 403 means the user have wrong role, but dont know what i did wrong. Any ideas?
Upvotes: 1
Views: 2209
Reputation: 513
Ok, i find it out. In SecurityConfig on ".hasRole(ERole.USER.name);" spring will attach ROLE_ prefix automatically. But the user have role USER and not ROLE_USER. I solved this problem in getAuthority()-method:
@Override
public String getAuthority() {
return "ROLE_" + this.name;
}
I know i use the SpringSecurity eventuelly not correct way, but this actuelly works for me (in my SpringBoot test project)
Upvotes: 4