【问题标题】:spring security getting 403 error [duplicate]春季安全收到403错误[重复]
【发布时间】:2017-09-19 22:52:04
【问题描述】:

在我的应用程序中,我尝试将“/user/**”权限授予 USER,将“/admin/**”权限授予管理员用户,但出现 403 错误。

我使用的是 Spring Boot 1.5.3

安全配置类:

package com.alokpanda.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(1)
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

     @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
            .authenticationProvider(authenticationProvider);
     }



     @Override
        protected void configure(HttpSecurity http) throws Exception {

                    http.authorizeRequests()
            .antMatchers("/", "/login", "/logout").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .usernameParameter("username")
            .passwordParameter("password")
            .loginProcessingUrl("/login")       
            .failureUrl("/")
            .and()
            .logout()
            //.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutUrl("/logout")
            .logoutSuccessUrl("/")
            .and()
            .csrf()
            .disable();
        } 

}

身份验证提供者类:

package com.alokpanda.security.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import com.alokpanda.security.service.CustomUserDetailsService;

@Service
public class AuthenticationProviderImpl extends AbstractUserDetailsAuthenticationProvider {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token)
            throws AuthenticationException {
        System.out.println(userDetails.getUsername());
        System.out.println(userDetails.getPassword());
        System.out.println(token.getCredentials());
        System.out.println(token.getCredentials().equals(userDetails.getPassword()));
        System.out.println(userDetails.getAuthorities());
            if(userDetails.getUsername() == null || token.getCredentials() == null) {
            throw new BadCredentialsException("Credential may not be null.");
        }

        if(!token.getCredentials().equals(userDetails.getPassword())) {
            System.out.println("Err");
            throw new BadCredentialsException("Invalid Credentials.");
        }

    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token)
            throws AuthenticationException {
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
        return userDetails;
    }

}

UserDetailsS​​ervice 类:

package com.alokpanda.security.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alokpanda.model.User;
import com.alokpanda.model.UserRole;
import com.alokpanda.repository.UserRepository;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

        for(UserRole userRole : user.getUserRole()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        UserDetails userDetails = (UserDetails) new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
        return userDetails;
    }

}

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    默认情况下,spring security会为你的角色添加ROLE_前缀。

    将数据库中的角色保存为ROLE_USERROLE_ADMIN

    【讨论】:

    • 在 spring boot 启动过程中出现错误“角色不应该以 'ROLE_' 开头,因为它是自动插入的。得到了 'ROLE_ADMIN'”
    • 然后在您的数据库中,尝试将角色保存为 ROLE_USER 和 ROLE_ADMIN
    猜你喜欢
    • 2016-10-27
    • 2012-12-27
    • 2013-12-22
    • 2014-02-25
    • 2014-02-02
    • 2012-12-13
    • 2017-11-30
    相关资源
    最近更新 更多