Spring Starter Security not authenticating - spring

When I add a User with "ROLE_USER" permissions, I am unable to authenticate. 401s are returned consistently when attempting to authenticate with username: "username" and password: "password".
I can see in the JSON that's output that the BCryptPasswordEncoder is encoding passwords as it should be, but regardless of whether I use the original password or encoded version, I'm still unable to authenticate.
I've been working on this for a couple of days to no avail. Is there anything I'm missing?
Code is below --
DatabaseLoader:
User user = new User("first", "last", "username", "password", "email", "phone", new String[] {"ROLE_USER"});
userRepository.save(user);
DetailsService:
#Component
public class DetailsService implements UserDetailsService {
#Autowired
UserRepository users;
#Override
public UserDetails loadUserByUsername(String userUsername) throws UsernameNotFoundException {
User user = users.findByUsername(userUsername);
if (user == null) {
throw new UsernameNotFoundException(userUsername + " was not found");
}
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getUserPassword(),
AuthorityUtils.createAuthorityList(user.getUserRoles())
);
}
}
WebSecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
DetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(User.PASSWORD_ENCODER);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf().disable();
}
}
User:
#Entity
public class User {
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
private long userId;
private String userFirstName;
private String userLastName;
private String username;
#JsonIgnore
private String userPassword;
private String userPhone;
private String userEmail;
#JsonIgnore
private String[] userRoles;
public User() {}
public User(String userFirstName, String userLastName, String username, String userPassword, String userPhone, String userEmail, String[] userRoles) {
this.userFirstName = userFirstName;
this.userLastName = userLastName;
this.username = username;
setUserPassword(userPassword);
this.userPhone = userPhone;
this.userEmail = userEmail;
this.userRoles = userRoles;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
#Column
public String getUserFirstName() {
return userFirstName;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
#Column
public String getUserLastName() {
return userLastName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
#Column
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = PASSWORD_ENCODER.encode(userPassword);
}
#Column
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
#Column
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
#Column
public String[] getUserRoles() {
return userRoles;
}
public void setUserRoles(String[] userRoles) {
this.userRoles = userRoles;
}
}

Your question isn't very clear about problem. But i guess you are stuck in user authentication with spring starter security.
You should check this question

Related

#AuthenticationPrincipal returns null

I setup my Spring Security application according to the reference document and after hours of troubleshooting I continue to get a null #AuthenticationPrincipal passed into my controller.
The authentication mechanism is working fine against the users in my database but still a null #AuthenticationPrincipal. I consulted several internet posts but still I am getting null.
WebSecurityConfig:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserService userService;
#Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider provider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(userService);
return provider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/registration").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(provider());
}
}
Message (entity):
#Entity
#Table(name = "sweater_message")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String text;
private String tag;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "user_id")
private User author;
public Message(String text, String tag, User user) {
this.author = user;
this.text = text;
this.tag = tag;
}
public Message() {
}
...getters and setters
User(entity):
#Entity
#Table(name = "sweater_user")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private boolean active;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "sweater_user_role",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id")
)
private Collection<Role> roles;
public User(String username, String password, boolean active, Collection<Role> roles) {
this.username = username;
this.password = password;
this.active = active;
this.roles = roles;
}
public User() {
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return isActive();
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles().stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
...getters and setters
}
UserService
#Service
public class UserService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
public User save(User user) {
User saveUser = new User(
user.getUsername(),
new BCryptPasswordEncoder().encode(user.getPassword()),
true,
Arrays.asList(new Role("USER")));
return userRepository.save(saveUser);
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User findUser = userRepository.findByUsername(username);
if (findUser == null) {
throw new UsernameNotFoundException("There is no user with this username");
}
return new org.springframework.security.core.userdetails.User(
findUser.getUsername(),
findUser.getPassword(),
mapRolesToAuthorities(findUser.getRoles()));
}
public Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles) {
return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toSet());
}
}
Controller:
#PostMapping("/main")
public String add(
#AuthenticationPrincipal User user,
#RequestParam String text,
#RequestParam String tag,
Map<String, Object> model
){
...user is null
}
try Changing #AuthenticationPrincipal User user to #AuthenticationPrincipal UserDetails userDetails since loadUserByUsername returns UserDetails
Using SecurityContextHolder.getContext().getAuthentication().getPrincipal() in your controller to see whether your userdetails object is stored in the right place since #AuthenticationPrincipal is an abbreviation for (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal().
For example:
#GetMapping("/all")
public ResponseEntity<String> test(#AuthenticationPrincipal AuthUserDetails userDetails) {
System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
return ResponseEntity.ok("success");
}
If the out print is something other than the UserDetails object, it means that you did not set Principal correctly when you are initializing your Authentication in the filter class. Let's use UsernamePasswordAuthenticationToken as an example:
// in filter class
#Component
public class JwtFilter extends OncePerRequestFilter {
private JwtProvider jwtProvider;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
Optional<AuthUserDetails> authUserDetailOptional = jwtProvider.resolveToken(request); // extract jwt from request, generate a userdetails object
if (authUserDetailOptional.isPresent()){
AuthUserDetails authUserDetails = authUserDetailOptional.get();
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
authUserDetails, // set your authUserDetails here!!
null,
authUserDetails.getAuthorities()
); // generate authentication object
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is not valid.");
}
}

Spring security authentication fails with Custom user

I am trying to authenticate with Custom User that implements UserDetails. Here is my custome User class. (This class is also extended by other classes like Citizen and Employee as well).
#Entity
#Table(name = "user")
#Inheritance(strategy = InheritanceType.JOINED)
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "phone")
private String phone;
#Column(name = "address")
private String address;
#Column(name = "status")
private boolean isActive;
#CreationTimestamp
#Column(name = "created_at")
private LocalDate createdAt;
#UpdateTimestamp
#Column(name = "updated_at")
private LocalDate updatedAt;
#Transient
private Set<GrantedAuthority> authorityList;
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return false;
}
#Override
public boolean isAccountNonLocked() {
return false;
}
#Override
public boolean isCredentialsNonExpired() {
return false;
}
#Override
public boolean isEnabled() {
return false;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorityList;
}
#Override
public String getPassword() {
return password;
}
public void setAuthorityList(Set<GrantedAuthority> authorityList) {
this.authorityList = authorityList;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public LocalDate getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDate updatedAt) {
this.updatedAt = updatedAt;
}
}
Also I have implemented UserDetailsService as
#Service
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
}
user.setAuthorityList(grantedAuthorities);
return user;// new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
}
}
And WebSecurityConfig as
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsServiceImpl userDetailsService;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/registration", "/newreport", "/login*", "/signin/**", "/signup/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.csrf().disable()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login").permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
#Override
protected UserDetailsService userDetailsService() {
return userDetailsService;
}
}
Authentication works find if i return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities); inside UserDetailsServiceImpl.
But as soon i return User class object user. Authentication fails.
I am not sure what i am missing here. Any help would be appreciated. Thanks in advance.
Because your UserDetails implementation always return false for the following methods:
#Override
public boolean isAccountNonExpired() {
return false;
}
#Override
public boolean isAccountNonLocked() {
return false;
}
#Override
public boolean isCredentialsNonExpired() {
return false;
}
#Override
public boolean isEnabled() {
return false;
}
In order to pass the authentication , all the above methods should return true.

I am unable to generate access token?

I am applying spring security in my project...and
I have a problem in my access token generation?
How can I generate access token ??
UserPrincipal
public class UserPrincipal implements UserDetails {
private Long id;
private String username;
private String emailAddress;
private String password;
private String phoneNumber;
private String age;
private String bio;
private String sex;
private String occupation;
private String partySupport;
private Date joiningDate;
private String status;
private Address address;
private Collection<? extends GrantedAuthority> authorities;
public UserPrincipal(Long id, String username, String emailAddress, String password, String phoneNumber, String age, String bio, String sex, String occupation, String partySupport, Date joiningDate, String status, Address address, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.emailAddress = emailAddress;
this.password = password;
this.phoneNumber = phoneNumber;
this.age = age;
this.bio = bio;
this.sex = sex;
this.occupation = occupation;
this.partySupport = partySupport;
this.joiningDate = joiningDate;
this.status = status;
this.address = address;
this.authorities = authorities;
}
public static UserPrincipal create(User user)
{
List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
new SimpleGrantedAuthority(role.getName().name())
).collect(Collectors.toList());
return new UserPrincipal(
user.getId(),
user.getUsername(),
user.getEmailAddress(),
user.getPassword(),
user.getPhoneNumber(),
user.getAge(),
user.getBio(),
user.getSex(),
user.getOccupation(),
user.getPartySupport(),
user.getJoiningDate(),
user.getStatus(),
user.getAddress(),
authorities
);
}
public Long getId() {
return id;
}
public String getEmailAddress() {
return emailAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getAge() {
return age;
}
public String getBio() {
return bio;
}
public String getSex() {
return sex;
}
public String getOccupation() {
return occupation;
}
public String getPartySupport() {
return partySupport;
}
public Date getJoiningDate() {
return joiningDate;
}
public String getStatus() {
return status;
}
public Address getAddress() {
return address;
}
#Override
public String getUsername() {
return username;
}
#Override
public String getPassword() {
return password;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserPrincipal that = (UserPrincipal) o;
return Objects.equals(id, that.id);
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
UserController
#RestController
#RequestMapping("/api")
#CrossOrigin(value = "http://localhost:4200", allowedHeaders = "*")
#Configuration
public class UserController {
#Autowired
private UserService userService;
#Autowired
private UserRepository userRepository;
#Autowired
private PollRepository pollRepository;
#Autowired
private VoteRepository voteRepository;
#Autowired
private PollService pollService;
private Object model;
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
#GetMapping("/user/all")
#PreAuthorize("hasRole('ADMIN')")
public List<User> getUsers() {
return userService.getUsers();
}
#GetMapping("/user/getCount")
#PreAuthorize("hasRole('ADMIN')")
public HashMap<String, String> getCount() {
int totalUsers = getUsers().size();
int activeUsers = userService.getCountByActive();
int inactiveUsers = userService.getCountByInactive();
HashMap<String, String> userStatus = new HashMap<>();
userStatus.put("Total",String.valueOf(totalUsers));
userStatus.put("Active", String.valueOf(activeUsers));
userStatus.put("Inactive",String.valueOf(inactiveUsers));
System.out.println(userStatus);
// System.out.println("Inactive Users" + inactiveUsers);
return userStatus;
}
#GetMapping("/user/{id}")
#PreAuthorize("hasRole('ADMIN')")
public Optional<User> getUser(#PathVariable Long id) {
return userService.getUser(id);
}
#DeleteMapping("/user/{id}")
#PreAuthorize("hasRole('ADMIN')")
public boolean deleteUser(#PathVariable Long id) {
userService.deleteUser(id);
return true;
}
#PutMapping("/user")
#PreAuthorize("hasRole('ADMIN')")
public User updateUser(#RequestBody User user) {
return userService.updateUser(user);
}
#PostMapping("/user")
public String createUser(#RequestBody User user) {
System.out.print("Email Address :" + user.getEmailAddress());
User user1 = userService.createUser(user);
if (user1 != null) {
return "success";
} else {
return "failed";
}
}
SecurityConfig
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CustomUserDetailsService customUserDetailsService;
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean(BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
firewall.setAllowUrlEncodedSlash(true);
return firewall;
}
#Override
public void configure(WebSecurity web) throws Exception {
web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/api/auth/**")
.permitAll()
.antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
.permitAll()
.antMatchers(HttpMethod.GET, "/api/polls/**", "/api/user/**")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
i tried in postman but there is an error 401 unauthorized shown..
i dont know what is the miss part which i have not added??
can anyone please suggest me what should i do??
Thanks in Advance!

Does the method getUsername() of interface UserDetails indicate that there must be a attribute "username" in an entity impl the interface?

I'm studying springboot on a website. The website gives a example project for spring security, following is a part of the code:
User entity:
#Entity
public class User implements UserDetails {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty(message = "name no empty")
#Size(min=2, max=20)
#Column(nullable = false, length = 20)
private String name;
#NotEmpty(message = "email no empty")
#Size(max=50)
#Email(message= "wrong email format" )
#Column(nullable = false, length = 50, unique = true)
private String email;
#NotEmpty(message = "username no empty")
#Size(min=3, max=20)
#Column(nullable = false, length = 20, unique = true)
private String username;
#NotEmpty(message = "password no empty")
#Size(max=100)
#Column(length = 100)
private String password;
#Column(length = 200)
private String avatar;
#ManyToMany(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
#JoinTable(name = "user_authority", joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "authority_id", referencedColumnName = "id"))
private List<Authority> authorities;
protected User(){
}
public User(Long id, String name, String username, String email){
this.id = id;
this.name = name;
this.email = email;
this.username = username;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
public void setUsername(String username){
this.username = username;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
for (GrantedAuthority authority : this.authorities){
simpleAuthorities.add(new SimpleGrantedAuthority(authority.getAuthority()));
}
return simpleAuthorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public void setPassword(String password) {
this.password = password;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
#Override
public String toString(){
return String.format("User[id = %d, name = '%s', username = '%s', email = '%s']", id, name, username, email);
}
}
UserService implementation:
#Service
public class UserServiceImpl implements UserService, UserDetailsService {
#Autowired
private UserRepository userRepository;
#Transactional
#Override
public User saveOrUpdateUser(User user) {
return userRepository.save(user);
}
#Transactional
#Override
public User registerUser(User user) {
return userRepository.save(user);
}
#Transactional
#Override
public void removeUser(Long id) {
userRepository.delete(id);
}
#Override
public User getUserById(Long id) {
return userRepository.findOne(id);
}
#Override
public Page<User> listUsersByNameLike(String name, Pageable pageable) {
name = "%" + name + "%";//匹配相似
Page<User> users = userRepository.findByNameLike(name, pageable);
return users;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findByUsername(username);
}
}
Security Configuration:
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private static final String KEY = "waylau.com";
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder);
return authenticationProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/admins/**").hasRole("ADMIN") /
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error")
.and().rememberMe().key(KEY)
.and().exceptionHandling().accessDeniedPage("/403");
http.csrf().ignoringAntMatchers("/h2-console/**");
http.headers().frameOptions().sameOrigin();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
}
What I focus is the attribute "username" of User.java. There is no problem when running codes above.
But after altered "username" to another name such as "accountname", it throws following exception
UserDetailsService returned null...
I know the problem is related to 'getUsername()'. This getter is also a overide method of UserDetails interface.
Take into consideration, the getter becomes this:
#Override
public String getUsername() {
return getAccountname();
}
But still not working. Does it mean the name of the attribute cannot be altered?

Spring Security roles are not working

I have configured spring security in my app,authentication is working well but authorization is not working mean #secured() annotation is not working.i am getting error when i access url "There was an unexpected error (type=Forbidden, status=403).
Access is denied".
My spring config is
#Autowired
private MongoDBAuthenticationProvider authenticationProvider;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**", "/css/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().defaultSuccessUrl("/resource")
.and().logout().and().authorizeRequests()
.antMatchers("/logout").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
.and().csrf().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
My controller is
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
UserService userService;
#Secured(value={"ROLE_ADMIN"})
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public void getUser() {
System.out.println("working");
}
}
Database user is
{ "_id" : ObjectId("555982a5360403572551660c"), "username" : "user", "password" : "pass", "role" : "ADMIN" }
My mongodb auth provider
#Service
public class MongoDBAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{
#Autowired
MongoUserDetailsService mongoUserDetailsService;
#Autowired MongoTemplate mongoTemplate;
#Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
}
#Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
UserDetails loadedUser;
try {
loadedUser = mongoUserDetailsService.loadUserByUsername(username);
} catch (Exception repositoryProblem) {
throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
}
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
}
}
User domain
public class User {
#Id
private String id;
#NotNull
private String name;
private int age;
private String username;
private String password;
private String role;
public User() {
super();
}
public User(String name,String username,
String password, String role) {
super();
this.name = name;
this.username = username;
this.password = password;
this.role = role;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
Add this bean in Spring Security Config File
#Bean
public RoleVoter roleVoter() {
RoleVoter roleVoter = new RoleVoter();
roleVoter.setRolePrefix("");
return roleVoter;
}
And write secured annotation like this
#Secured(value={"ADMIN"})
#Secured(value={"ADMIN"})
Instead of
#Secured(value={"ROLE_ADMIN"})
You also could try
#PreAuthorize("hasRole('ADMIN')")
If #Secured annotation still doesn't work

Resources