Steven Luo
Steven Luo

Reputation: 2548

Spring Security Access Denied

I am using Spring Security 4 and meet the following problem.

Here is the spring-security.xml

<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**"  access="hasRole('ADMIN')" />
</http>

<authentication-manager>
  <authentication-provider user-service-ref="customUserDetailsService">
    <password-encoder hash="plaintext" />
  </authentication-provider>
</authentication-manager>

This is the user detail service:

@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

@Autowired
private UserDAO userDAO;    

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    // TODO Auto-generated method stub
    com.hersbitcloud.cancercloud.models.User instance = new com.hersbitcloud.cancercloud.models.User(username, null, null);
    com.hersbitcloud.cancercloud.models.User domainUser = userDAO.findByExample(instance).get(0);

    List<GrantedAuthority> setAuths = new ArrayList<GrantedAuthority>();
    setAuths.add(new SimpleGrantedAuthority(domainUser.getRole()));

    User user = new User(
            domainUser.getUsername(), 
            domainUser.getPassword(), 
            setAuths
    );

    return user;

}    

When I navigate to /admin page, the login page shows up. And I use the username and password which I am sure has the role ADMIN because it can varified by Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();.

However, once I get authorized, it shows HTTP Status 403 - Access is denied. Which I think means the username and password is correct but there's something wrong with the role.

What is the problem?

Upvotes: 0

Views: 680

Answers (1)

Jaganath Kamble
Jaganath Kamble

Reputation: 556

Problem is with your role it should be ROLE_ADMIN

Upvotes: 1

Related Questions