当前位置: 首页 > 知识库问答 >
问题:

Spring Security总是在登录后返回403 accessDeniedPage[重复]

长孙阳成
2023-03-14

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

用户只有一个角色。该方法返回具有超级用户角色的用户。

这是我的Spring Security配置类

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

这是我的UserDetailsServiceImpl类

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

在我提供正确的用户名和密码后,这个方法总是返回一个用户。这就是它的回报

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

这是控制器类

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

共有1个答案

白才艺
2023-03-14

Userme,你是如何为安全的UserDetails对象建立角色名的?

请注意,根据Spring Security的架构决定,您必须向您的权限预告ROLE_:

new SimpleGrantedAuthority("ROLE_" + roleName);

Att

 类似资料:
  • 我在Android Studio上写过Java代码。我做了登录方法,在我的代码中发生了一些事情。它没有返回正确的返回值。返回值始终为false。虽然我在Android Studio上检查了函数,但是布尔变量已经正确地改变了,但是它在方法的末尾又改变了,所以登录方法总是返回false&我无法继续登录。 请帮我解决这个困惑的时刻。任何回答都将不胜感激,非常感谢。

  • 问题内容: 我正在做一个简单的论坛,由一系列论坛组成,每个论坛分别代表首页,主题,postitit,登录名和用户列表页面。在某些页面上,当用户未登录时会出现一个链接。 我想要实现的是在登录后触发重定向(在RequestDispatcher上使用forward()),以便浏览器返回到用户在单击登录链接之前所在的页面。为此,我看到了两种解决方案。 第一种解决方案是使用带有登录按钮的HTML 和一个不可

  • 接口说明 登录并返回token 如需调用,请访问 开发者文档 来查看详细的接口使用说明 该接口仅开放给已获取SDK的开发者 如开启https功能,请求地址的协议应改为https,如:https://www.example.com/wish3dearth/api/access/v1.0.0/getLicenseInfo API地址 POST /authcenter/api/login/v1.0.0/

  • 问题内容: 这个问题已经在这里有了答案 : 私人成员的Java反射getFields | 动态访问对象名称值 (2个答案) 7年前关闭。 我正在尝试获取特定类中的字段数。但是我使用的技术无法正常工作,并且始终返回0: 如何获得特定类别的字段计数? 问题答案: 用法 该方法适用于可访问的公共字段- 请参阅文档。

  • 当使用signInWithEmailAndPassword()API在firebase中进行身份验证时,我无法获得有效的“当前”用户。 我使用用户名和密码登录应用程序 我一旦登录,用户就会被带到主页 我试图获取用户的UID,但是没有返回有效的用户。调用发生在异步函数中,如下所示: 当前用户为空。 知道是什么引起的吗?

  • 这是我的代码,我不知道为什么我的bean没有被注入,它在构造函数中总是空的 下面是我的配置类: 我的堆栈跟踪 启动ApplicationContext时出错。若要显示自动配置报告,请在启用“debug”的情况下重新运行应用程序。11:55:29.139[restartedMain]错误O.S.Boot.SpringApplication-应用程序启动失败org.SpringFramework.Be