springboot中使用springsecurity,登录url就出现403错误

金色的鱼儿      2022-05-19     401

关键词:

参考链接:https://segmentfault.com/q/1010000012743613

有两个controller,一个是所有用户可以访问的@RequestMapping("user"),
还有一个是管理员可以访问的@RequestMapping("admin")。

/user/login是UserController中的登录url。
所有操作(除登录注销)都要登录之后才能进行。

现在想用springboot结合spring security实现权限管理。
系统是前后端分离的,controller中返回数据,不返回页面,WebMvcConfig也没有配置什么。

但/user/login,post怎么也不通。报403错误。

这是错误信息

 

 这是WebSecurityConfig

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService() { //注册UserDetailsService 的bean
        return new CustomUserService();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("hasRole('ROLE_USER')")
                .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                .anyRequest().authenticated().and() // access after login
//                .rememberMe().tokenValiditySeconds(60 * 60 * 24 * 7).key("").and()
                .formLogin().loginProcessingUrl("user/login").permitAll().and()
                .logout().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }
}

这是CustomUserService

@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("loadUser " + s);
        User user = userService.getUserByUsername(s);
        if (user == null || user.getIsDel() == 1) {
            throw new UsernameNotFoundException("user not exist");
        }
        List<GrantedAuthority> auths = new ArrayList<>();
        for (Role role : user.getRoles()) {
            auths.add(new SimpleGrantedAuthority(role.getName())); //不同用户会返回不同的role.name:ROLE_USER, ROLE_ADMIN
        }
        return new org.springframework.security.core.userdetails.User(s , user.getPwd(), auths);
    }
}

最后即使我在WebSecurity中什么也不配置,默认应该是不需要验证session吧。
仍然不行。

protected void configure(HttpSecurity http) throws Exception {
}

 

问题原因及解决方案:

看错误提示,可能是因为你开启了CSRF保护,关闭即可,在configure(HttpSecurity http)方法中追加http.csrf().disable();

 

使用 HTTP 标头的 Spring Security

】使用HTTP标头的SpringSecurity【英文标题】:SpringSecurityusingHTTPheaders【发布时间】:2017-10-2200:08:05【问题描述】:我正在尝试为我的SpringBoot应用程序添加安全性。我当前的应用程序正在使用REST控制器,每次收到GET或POST请求时,我... 查看详情

Spring Boot 我无法切换 keycloak 和基本身份验证

...启动时在基本身份验证和SSO之间进行选择。所以我首先将SpringSecuri 查看详情

认证和授权学习2:springboot中快速使用springsecurity

认证和授权学习2:springboot中快速使用springsecurity本文以一个示例工程记录下如何在springboot工程中快速的使用springsecurity,使用的springboot版本是目录认证和授权学习2:springboot中快速使用springsecurity一、创建工程,导入依赖二、默认... 查看详情

springboot中使用javamailsender发送邮件

...Spring提供了非常好用的JavaMailSender接口实现邮件发送。在SpringBoot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在SpringBoot中使用JavaMailSender发送邮件。快速入门在SpringBoot的工程中的pom.xml中引入spring-boot-starter-mail... 查看详情

springboot中使用thymeleaf

SpringBoot支持FreeMarker、Groovy、Thymeleaf和Mustache四种模板解析引擎,官方推荐使用Thymeleaf。spring-boot-starter-thymeleaf在SpringBoot中使用Thymeleaf只需在pom中加入Thymeleaf的starter即可:1234<dependency><groupId>org.sprin 查看详情

springboot中使用kafka

...oducer、以及consumer后,尝试在JAVA中使用Kafka。使用IDEA创建SpringBoot项目这个使用IDEA创建一个新的SpringBoot项目就可以,也可以在https://start.spring.io/下载一个新的项目。配置依赖 pom文件如下:1<?xmlversion="1.0" 查看详情

在springboot中使用httpinvoker

https://blog.csdn.net/qq_34741165/article/details/88146067 在Spring中使用HttpInvoker在官方文档中已经描述的很清楚了,那么,在SpringBoot中怎么使用呢?首先我们定义一个接口:publicinterfaceITestService{Stringtest(Stringhello);} 查看详情

springboot中使用jdbctemplate

本文将介绍如何将springboot与JdbcTemplate一起工作。Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。JdbcTemplate是在JDBCAPI基础上提供了更抽象的封装,并提供了基于方法... 查看详情

springboot中如何使用外置tomcat服务器

文章目录SpringBoot中如何使用外置tomcat服务器1.确保springboot项目的打包方式是war2.引入外部的tomcat依赖坐标3.把外部的tomcat服务器引入到IDEA中4.启动外部tomcat服务器5.配置tomcat服务器的访问接口SpringBoot中如何使用外置tomcat服务器1.... 查看详情

如何在springboot中使用handlermethodargumentresolver

本例子是使用HandlerMethodArgumentResolver方便的获取session中的内容。 SessionInfo.java在session中存储用户数据...publicclassSessionInfo{privateIntegeruserId;privateStringusername;privateStringua;privateStringip;...//const 查看详情

springboot中使用redissession

  springboot默认的httpsession是存在内存中。这种默认方式有几个缺点:1、当分布式部署时,存在session不一致的问题;2、当服务重启时session就会丢失,这时候用户就需要重新登陆,可能导致用户数据丢失。通常会使用redis来保存... 查看详情

springboot中commandlinerunner的使用

https://blog.csdn.net/BBQ__ZXB/article/details/126181495 查看详情

springboot中使用servlet,方法一

 首页,我也不知道什么场景下SpringBoot才会使用Servlet,有知道的可以评论告诉我,谢谢!!!一、先上完整的目录结构:二、使用SpringBoot后,就没有web.xml文件了,所以我们配置Servlet使用注解@WebServlet:MyServlet.java文件内容:... 查看详情

在springboot中使用@configurationproperties注解

...在mail.properties文件中。属性必须命名规范才能绑定成功。SpringBoot使用一些松的规则来绑定属性到@ConfigurationProperties bean并且支持分层结构(hierarchicalstructure)。开始创建一个@ConfigurationProperties bean: @Configur 查看详情

在springboot工程中使用filter

在springboot工程中使用filter一、什么是filter过滤器实际上就是用来对web资源进行拦截,做一些处理后再交给下一个过滤器或servlet处理通常都是用来拦截request进行处理的,也可以对返回的response进行拦截处理。filter可以在请求到达s... 查看详情

springboot中使用esper入门

参考技术Aesper是一个比较经典的CEP(ComplexEventProcessing)的开源实现(开源协议为GPLv2),这里简单介绍下如何在springboot中使用。在esper-6.1.0-sources.jar!/com/espertech/esper/core/service/EPServiceProviderImpl.java的构造器中也调用了初始化 查看详情

如何使用 JWT Authentication 在 springboot 中使用 html 模板?

】如何使用JWTAuthentication在springboot中使用html模板?【英文标题】:HowtousehtmltemplateinspringbootusingJWTAuthentication?【发布时间】:2020-01-3121:05:16【问题描述】:几天来,我开始学习使用springboot,尤其是使用springsecurity进行用户身份验... 查看详情

在springboot中使用https

https://www.jianshu.com/p/8d4aba3b972dhttps://www.jdon.com/49625 查看详情