对于登录接口,登录成功后的响应,登录失败后的响应,我们都可以在 WebSecurityConfigurerAdapter 的实现类中进行配置。例如下面这样
(以下内容是springboot项目配置好基础spring security以后的内容,spring security的基本配置这里就不重复了。)
下面来详细解释配置的代码:
以下定义了两个访问路径分别所需的权限,除了以admin和user开头的路径其他路径的当问不需要权限:
.antMatchers("/admin/**").hasRole("admin")
.antMatchers("user/**").hasAnyRole("admin","user")
.anyRequest().authenticated()
设置登陆接口,如果用postman测试需要这个接口:
.and()
.formLogin()
.loginProcessingUrl("/doLogin") //登陆接口
当我们访问需要登陆的路径时会自动跳转到跳转到/login路径
.loginPage("/login") //登陆页面
定义登陆时,用户名的key默认是username,这里改为uname
密码的key默认是password,这里改为passwd。
.usernameParameter("uname")
.passwordParameter("passwd")
我们可以在 successHandler 方法中,配置登录成功的回调,如果是前后端分离开发的话,登录成功后返回 JSON 即可
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp,
Authentication authentication) throws IOException, ServletException {
设置数据格式为json类型
resp.setContentType("application/json;charset=utf-8");
这里配置登陆成功之后的状态码以及信息
PrintWriter out = resp.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("status",200);
map.put("msg",authentication.getPrincipal());
out.write(new ObjectMapper().writeValueAsString(map));
登陆失败和成功的配置道理是一样的,只是多了登陆失败具体原因的判断:
如下针对登陆失败的不同原因进行具体解释(以便于我们及时查错)
if (e instanceof LockedException) {
map.put(&#

最低0.47元/天 解锁文章
616

被折叠的 条评论
为什么被折叠?



