与servlet Api 的集成

Servlet API集成与Spring Security
本文介绍了Servlet API的集成使用,包括如何通过HttpServletRequest获取用户信息、检查用户角色、执行登录和登出操作等。此外还介绍了如何利用Servlet 3及更高版本的功能进行异步操作,并确保安全性。

Servlet APi 集成

Servlet 2.5+ Integration

15.1.1 HttpServletRequest.getRemoteUser()得到用户名.

15.1.2 HttpServletRequest.getUserPrincipal()

HttpServletRequest.getUserPrincipal()得到SecurityContextHolder.getContext().getAuthentication()的信息.

Authentication auth = httpServletRequest.getUserPrincipal();
// assume integrated custom UserDetails called MyCustomUserDetails
// by default, typically instance of UserDetails
MyCustomUserDetails userDetails = (MyCustomUserDetails) auth.getPrincipal();
String firstName = userDetails.getFirstName();
String lastName = userDetails.getLastName();

15.1.3 HttpServletRequest.isUserInRole(String)

是否有角色

boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");

15.2 Servlet 3+ Integration

15.2.1 HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)

HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) 可以保证用户被认证.如果用户没被认证,AuthenticaitonEntryPoint触发认证.

15.2.2 HttpServletRequest.login(String,String)

登陆

try {
httpServletRequest.login("user","password");
} catch(ServletException e) {
// fail to authenticate
}

15.2.3 HttpServletRequest.logout()

登出

AsyncContext.start(Runnable)

异步操作

final AsyncContext async = httpServletRequest.startAsync();
async.start(new Runnable() {
	public void run() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		try {
			final HttpServletResponse asyncResponse = (HttpServletResponse) async.getResponse();
			asyncResponse.setStatus(HttpServletResponse.SC_OK);
			asyncResponse.getWriter().write(String.valueOf(authentication));
			async.complete();
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
});

异步输出用户信息

Async Servlet Support

servlet至少是3.0

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

</web-app>

下一步添加DelegatingFilterProxy的异步支持

filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
	org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>

15.3 Servlet 3.1+ Integration

15.3.1 HttpServletRequest#changeSessionId()

可以用来对抗session固定攻击.

转载于:https://my.oschina.net/u/1590027/blog/913448

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值