Spring Security 出现 403 错误 [英] spring security getting 403 error

查看:138
本文介绍了Spring Security 出现 403 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我试图向 USER 授予/user/**"权限,向管理员用户授予/admin/**"权限,但出现 403 错误.

In my application i am trying to give "/user/** " permission to USER and "/admin/**" permission to admin user but I am getting 403 error.

我使用的是 Spring Boot 1.5.3

I am using 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 类:

UserDetailsService class :

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;
    }

}

推荐答案

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

By default, spring security add ROLE_ prefix to your roles.

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

Save the roles in your DB as ROLE_USER and ROLE_ADMIN.

这篇关于Spring Security 出现 403 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆