Spring Security始终在登录后返回403 accessDeniedPage [英] Spring Security always return the 403 accessDeniedPage after login

查看:1162
本文介绍了Spring Security始终在登录后返回403 accessDeniedPage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring的新手,我一直在尝试使用Spring Security实现一个简单的登录页面.但是,在提供登录凭据后,它始终会访问拒绝的url".我提供正确的用户名和密码后,loadUserByUsername()方法始终返回一个用户.但是我不知道如何找到返回该用户对象后发生的情况.

I am new to Spring and I have been trying to implement a simple login page using spring security. But it always goes to access Denied url after providing the login credentials. loadUserByUsername() method always returns a user after I provide correct username and password. But I don't know how to find what happens after that user object is returned.

用户只有一个角色.然后该方法返回具有SUPER_USER角色的用户.

A user has only one role. And the method returns user with SUPER_USER role.

这是我的spring安全配置类

here is my spring security configuration class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = AppConfig.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {

        System.out.println("Inside configureGlobalSecurity method");

        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("Inside configure method");
        http.authorizeRequests().antMatchers("/", "/list")
                .access("hasRole('SUPER_USER') or hasRole('NORMAL_USER') or hasRole('CUSTOMER')")
                .and().formLogin().loginPage("/login")
                .loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password").and()
                .csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        System.out.println("Inside authenticationProvider method");
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }


    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }
} 

这是我的UserDetailsS​​erviceImpl类

This is my UserDetailsServiceImpl class

import java.util.HashSet;
import java.util.Set;

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 org.springframework.transaction.annotation.Transactional;

import com.dao.user.UserDao;
import com.entity.user.User;

@Service("userDetailsService")
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserDao userDao = null;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.getUserByUsername(username);
        if(user!=null) {
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            grantedAuthorities.add(new SimpleGrantedAuthority(user.getRole().getDescription().getStringVal()));
            org.springframework.security.core.userdetails.User u = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true,grantedAuthorities);
            return u;
        } else {
            throw new UsernameNotFoundException("User Does not Exist");
        }
    }
}

此方法总是在我提供正确的用户名和密码后返回用户.这就是返回的结果

This method always returns a user after i provide the correct username and password.This is what it returns

org.springframework.security.core.userdetails.User@a3b: Username: RM; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: SUPER_USER

这是Controller类

This is the Controller class

import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/")
public class LoginController {


@Autowired
AuthenticationTrustResolver authenticationTrustResolver;


@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {

    System.out.println("Inside controller list");

    return "first";
}



@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
@ResponseBody
public String accessDeniedPage(ModelMap model) {

    return "Access Dennied";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
    System.out.println("Inside controller login");
    if (isCurrentAuthenticationAnonymous()) {
        return "login";
    } else {
        return "redirect:/list";  
    }
}


@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    

        SecurityContextHolder.getContext().setAuthentication(null);
    }
    return "redirect:/login?logout";
}


/**
 * This method returns true if users is already authenticated [logged-in], else false.
 */
private boolean isCurrentAuthenticationAnonymous() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authenticationTrustResolver.isAnonymous(authentication);
}

这是我的登录表格

<form id="login" name="login" class="form-signin" action="/SpringView/login" method=POST>
    <span id="reauth-email" class="reauth-email"></span>
    <input type="text" id="username" name="username" class="form-control" placeholder="Email address" required
           autofocus>
    <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
    <div id="remember" class="checkbox">
        <label>
            <input type="checkbox" value="remember-me"> Remember me
        </label>
    </div>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <button class="btn btn-lg btn-block btn-signin " type="submit">Sign in</button>
</form><!-- /form -->

推荐答案

Userme,您如何为Security的UserDetails对象构建角色名称?

Userme, how are you building the role name to Security's UserDetails object?

请注意,通过Spring Security的

Please, note that by a Spring Security's architectural decision you must prepend 'ROLE_' to you authority:

new SimpleGrantedAuthority("ROLE_" + roleName);

Att

这篇关于Spring Security始终在登录后返回403 accessDeniedPage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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