spring security

捞捞会spring security的佬,有偿
我这边登陆成功后端显示是管理员身份但是还是不能跳转页面

img

img

img

可以借鉴下

实现授权需要对用户的访问进行拦截校验,校验用户的权限是否可以操作指定的资源,Spring Security默认提供授

权实现方法。

在LoginController添加/r/r1或/r/r2

 /**
     * 测试资源1
     * @return
     */
    @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"})
    public String r1(){
        return " 访问资源1";
    }

    /**
     * 测试资源2
     * @return
     */
    @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"})
    public String r2(){
        return " 访问资源2";
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
在安全配置类WebSecurityConfifig.java中配置授权规则:

.antMatchers("/r/r1").hasAuthority("p1") .antMatchers("/r/r2").hasAuthority("p2")
1
.antMatchers("/r/r1").hasAuthority(“p1”)表示:访问/r/r1资源的 url需要拥有p1权限。

.antMatchers("/r/r2").hasAuthority(“p2”)表示:访问/r/r2资源的 url需要拥有p2权限。

完整的WebSecurityConfifig方法如下:

  //安全拦截机制(最重要)
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/r/r1").hasAuthority("p1")
                .antMatchers("/r/r2").hasAuthority("p2")
                .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过
                .anyRequest().permitAll()//除了/r/**,其它的请求可以访问
                .and()
                .formLogin()//允许表单登录
                .successForwardUrl("/login-success");//自定义登录成功的页面地址

    }



可能是controller中使用的路径为login,在没有学配置文件情况下。

//正确使用
    @RequestMapping("/hello")
    public String login(){
        return "登录成功";
    }

//    错误的使用
    @RequestMapping("/login")
    public String errologin(){
        return "登录成功";

具体卡在哪个地方?可以将代码贴出来看下

  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/746656
  • 这篇博客你也可以参考下:Spring security登录 显示用户名不存在或者密码错误
  • 除此之外, 这篇博客: Spring Security 实战干货:实现自定义退出登录中的 2. 我们使用 Spring Security 登录后都做了什么 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 这个问题我们必须搞清楚!一般登录后,服务端会给用户发一个凭证。常见有以下的两种:

    • 基于 Session 客户端会存 cookie 来保存一个 sessionId ,服务端存一个 Session

    • 基于 token 客户端存一个 token 串,服务端会在缓存中存一个用来校验此 token 的信息。

  • 您还可以看一下 银文杰老师的Spring Security 实战精讲——基础篇课程中的 最简单的Spring Security程序入门示例小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    对于这个问题,建议先检查一下配置文件中是否配置了正确的权限和页面跳转路径。其次,可以检查一下登录成功后返回的信息是否包含用户身份信息,如果没有,可以考虑在登录成功后手动设置用户身份信息。如果存在身份信息而无法跳转页面,可能是因为跳转路径没有配置正确或者存在权限问题,需要进一步排查。另外,需要确认使用的密码加密方式是否和配置文件中一致,如果不一致,建议使用 DelegatingPasswordEncoder 来兼容多种加密方式。代码示例:

    在配置文件中添加权限和页面跳转配置:

    spring:
      security:
        # 配置权限
        authorizeRequests:
          antMatchers("/admin/**").hasRole("ADMIN")
          antMatchers("/user/**").hasRole("USER")
          # 配置登录页和登录处理页
        formLogin:
          loginPage: /login
          loginProcessingUrl: /doLogin
          # 配置登录成功后的跳转页面
        defaultSuccessURL: /index
    

    在登录成功后通过设置用户身份信息:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    List<GrantedAuthority> authorities = new ArrayList<>();
    // 添加用户权限
    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    // 构建用户身份信息
    UserDetails userDetails = new User("username", "password", authorities);
    Authentication newAuth = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(newAuth);
    

    在使用密码加密时,建议使用 DelegatingPasswordEncoder,示例代码:

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
    

    对于无法跳转页面的问题,可以尝试在配置文件中添加以下配置:

    spring:
      security:
        # 关闭CSRF保护
        csrf:
          enabled: false
        # 允许FrameOptions显示
        headers:
          frameOptions:
            mode: SAMEORIGIN
    

    以上就是解决 Spring Security 登陆成功后无法跳转页面的几个常见方法,希望对你有所帮助。如果还有问题,欢迎进一步沟通。

以下答案由GPT-4.0Plus大模型与博主A努力中.......共同编写:
根据您的描述,Spring Security登陆成功后无法跳转页面,这通常有以下几个原因:

  1. 权限不足:Spring Security默认会对URL进行权限控制,即使登陆成功,如果当前用户没有访问某个URL的权限,也无法正常跳转。您可以检查一下当前用户对要跳转的URL是否具有VIEW权限。
  2. 会话过期:如果当前会话(Session)已经过期,Spring Security也无法正常跳转。您可以检查一下Spring Security的会话超时时间session-timeout大小,及时更新会话。
  3. CSRF token错误:如果当前请求没有包含正确的CSRF token,Spring Security会阻止跳转以防止CSRF攻击。您需要确保所有POST请求都包含CSRF token。
  4. 未设置default-target-url:如果登录成功后Spring Security找不到要跳转的默认页面URL,它也无法正常跳转。您需要在Spring Security配置中设置default-target-url指定登录成功后的跳转页面。
  5. 其他过滤器阻止了请求:除Spring Security外,如果其他过滤器(Filter)阻止了当前请求,也会导致无法跳转。需要检查其他过滤器的配置,确保登录成功后的请求可以正常通过。

建议您根据上述可能原因进行检查,常见的解决方案有:

  1. 检查用户对要访问URL的权限,并授予足够权限;
  2. 增大会话超时时间;
  3. 确认所有POST请求都包含CSRF token;
  4. 在SecurityConfig中设置default-target-url;
  5. 检查其他过滤器的配置,不阻止登录成功后的请求。

以下答案由GPT-3.5大模型与博主波罗歌共同编写:
那么这个问题有可能是由于权限配置不正确导致的。在 spring security 中,通常会通过配置 WebSecurityConfigurerAdapter 类来完成权限配置,在该类中重写 configure(HttpSecurity http) 方法可以配置相关的权限控制规则。

首先,需要确定自己希望在管理员登录成功后能够访问哪些页面或资源。这些页面或资源被定义为"有权访问的资源"。

其次,需要确定哪些账号具备管理员权限。这些账号被定义为"管理员账号"。

最后,需要在 WebSecurityConfigurerAdapter 类的 configure(HttpSecurity http) 方法中配置相应的权限控制规则,给 "有权访问的资源" 分配 "角色",给 "管理员账号" 分配 "角色",并将 "角色" 和 "权限" 关联。

以下是一个关于如何配置 spring security 初步权限的示例代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            //配置"/login"路径不需要权限访问
            .antMatchers("/login").permitAll()
            //配置"有权访问的资源"路径需要"ROLE_USER"角色访问
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            //配置登录页面
            .formLogin()
            .loginPage("/login")
            //配置登录成功跳转页面
            .defaultSuccessUrl("/admin/index")
            .permitAll()
            .and()
            .logout()
            //配置退出路径和退出后跳转页面
            .logoutUrl("/logout")
            .logoutSuccessUrl("/")
            .permitAll();
    }
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //配置"用户"和"角色"
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop}123456").roles("USER")
            .and()
            .withUser("admin").password("{noop}123456").roles("ADMIN");
    }

}

上述代码中,通过 configure(HttpSecurity http) 方法配置了对 "/login" 路径的访问权限和对 "/admin/" 路径的权限控制规则。其中 "/admin/" 路径是 "有权访问的资源"。管理员账号为 "admin",该账号的密码为 "123456",并且该账号被赋予了 "ADMIN" 角色。
如果我的回答解决了您的问题,请采纳!

发代码出来看一看