Spring security登录授权验证的简单例子

response.sendRedirect(“/index”);

}

})

.permitAll()

.and();

//http.rememberMe().tokenValiditySeconds(5);

http

.authorizeRequests() // 配置认证与授权

.antMatchers(“/user/**”).hasRole(USER) //基于角色

//.antMatchers(“/user/**”).hasAuthority(“p1”) 基于权限

.antMatchers(“/admin/**”).hasRole(ADMIN) //基于角色

//.antMatchers(“/admin”, “/admin/**”).hasAuthority(“p2”) 基于权限

//.hasAnyAuthority(“admin,manager”) 只要有任意一个权限就可访问, 多个权限逗号分隔

.anyRequest().authenticated() //需登录才能访问。

.and();

//注销登录,退出当前用户

http.logout()

.logoutUrl(“/logout”)

.logoutSuccessHandler(new LogoutSuccessHandler() {

@Override

public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {

// resp.setContentType(“application/json;charset=utf-8”);

// PrintWriter out = resp.getWriter();

// out.write(“退出登录”);

// out.flush();

// out.close();

resp.sendRedirect(“/login”);

}

})

.logoutSuccessUrl(“/login”)

.permitAll()

.and();

}

@Override

public void configure(AuthenticationManagerBuilder auth) throws Exception {

auth.inMemoryAuthentication()

.withUser(“admin”)

//.authorities(“p1”, “p2”) 基于权限

.password(“admin”).roles(USER, ADMIN) //基于角色

.and()

.withUser(“fly”)

//.authorities(“p1”) 基于权限

.password(“123456”).roles(USER) //基于角色

.and()

.passwordEncoder(new MyPasswordEncoder());

}

}

权限为user的角色,只能访问user下的页面。admin角色可以访问所有页面。在代码中创建了两个账户,admin和fly,admin为“admin”角色,fly为“user”角色。

spring security默认自带有一个login的页面。除非代码中指定,否则,formLogin()默认启用就是spring security自带的login页面。

上面的代码中用到了MyPasswordEncoder,自定义实现的:

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder {

@Override

public String encode(CharSequence rawPassword) {

return rawPassword.toString();

}

@Override

public boolean matches(CharSequence rawPassword, String encodedPassword) {

return rawPassword.equals(encodedPassword);

}

}

接下来写一个页面的controller控制器:

import org.springframework.security.access.annotation.Secured;

import org.springframework.security.authentication.AnonymousAuthenticationToken;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

import org.springframework.security.core.Authentication;

import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@Controller

@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)

public class MyWebPageController {

@GetMapping(“/user/{username}”)

@ResponseBody //表示当前函数完成对于当前路由请求的处理后,并把返回的结果直接给浏览器。

public String getUser(@PathVariable String username) {

return username;

}

@GetMapping(“”)

public void redirectToindex(HttpServletResponse response) {

try {

//重定向

response.sendRedirect(“/login”);

} catch (Exception e) {

e.printStackTrace();

}

}

@GetMapping(“/index”)

@ResponseBody

public String index() {

String info_name = “未登录用户”;

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (!(authentication instanceof AnonymousAuthenticationToken)) {

info_name = authentication.getName();

}

return info_name + “@index@” + System.currentTimeMillis();

}

@GetMapping(“/admin”)

@ResponseBody

public String adminPage(Authentication authentication) {

return authentication.getName() + “@” + System.currentTimeMillis();

}

@GetMapping(“/user”)

@ResponseBody

public String userPage(Authentication authentication) {

return "user " + authentication.getName() + “@” + System.currentTimeMillis();

}

@GetMapping(“/whoami”)

@ResponseBody

public String whoami(Authentication authentication) {

//返回当前登录用户是谁?

return "I am " + authentication.getName() + “@” + System.currentTimeMillis();

}

@GetMapping(“/super”)

@Secured({“ROLE_admin”})

@ResponseBody

public String superUser(Authentication authentication) {

//返回当前登录用户是谁?

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img
线程、数据库、算法、JVM、分布式、微服务、框架、Spring相关知识

一线互联网P7面试集锦+各种大厂面试集锦

学习笔记以及面试真题解析

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
微服务、框架、Spring相关知识

[外链图片转存中…(img-C8FLLVC3-1713303080202)]

一线互联网P7面试集锦+各种大厂面试集锦

[外链图片转存中…(img-lIgYCXEj-1713303080202)]

学习笔记以及面试真题解析

[外链图片转存中…(img-E2Le2al4-1713303080202)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值