您的位置:首页 > 编程语言 > Java开发

spring security3入门

2015-06-26 11:36 525 查看
由于工作需要,学习了一下spring security ,与之前学习的apache shiro相比,spring security确实复杂了不少。下面是学习的一下记录

1、web.xml引入过滤器:

<pre name="code" class="html"><span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:spring-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app></span>




名字必须是springSecurityFilterChain,不然你得自己定义bean了

2、spring-sesurity.xml配置:

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

<sec:http entry-point-ref="authenticationEntryPoint" auto-config="true" access-decision-manager-ref="accessDecisionManager">
<sec:intercept-url pattern="/login.html" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<sec:intercept-url pattern="/user/test*" access="AUTH_ADMIN"/><!-- 拥有admin权限才能访问 -->
<sec:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/><!-- 登录或者具有user角色就能访问 -->
<sec:custom-filter after="FORM_LOGIN_FILTER" ref="authenticationFilter"/>
<sec:logout logout-url="/logout" delete-cookies="JSESSIONID"/>
</sec:http>

<!-- 登录入口 可以记录认证前的请求地址-->
<bean id="authenticationEntryPoint" class="com.plateno.interceptor.TerryLoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="/login.html"/>
</bean>

<!-- 用户名密码匹配 -->
<!-- <bean id="authenticationFilter" class="com.plateno.interceptor.TerryAuthenticationFilter"> -->
<bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"/>
<property name="usernameParameter" value="username"/>
<property name="passwordParameter" value="password"/>
<property name="filterProcessesUrl" value="/doLogin.html"></property><!-- 这个url位登录提交url,必须验证 -->
<property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
</bean>

<!-- 身份证验证的 -->
<bean id="terryAuthenticationProvider" class="com.plateno.interceptor.TerryAuthenticationProvider"></bean>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="terryAuthenticationProvider"/>
</sec:authentication-manager>

<!-- 认证成功后调整处理 -->
<bean id="authenticationSuccessHandler" class="com.plateno.interceptor.TerryAuthenticationSuccessHandler"></bean>

<!-- 投票决定是否允许访问 -->
<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"><!-- 判断用户具有某一角色才能访问 -->
<property name="rolePrefix" value="AUTH_"></property>
</bean>
<bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"></bean><!-- 只能决定用户登录or非登录or rememberMe这样三种情况 -->
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased"><!-- 权限控制,只要符合一种,就能访问;还有一种是多数服从少数,还有一种是一票否决 -->
<property name="decisionVoters">
<list>
<ref bean="authenticatedVoter"/>
<ref bean="roleVoter"/>
</list>
</property>
</bean>

</beans></span>


注释已经写得很清楚了

3、下面是主要的一些类:

认证成功后回调的类:

<span style="font-size:18px;">package com.plateno.interceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class TerryAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
String ru = (String)request.getSession().getAttribute("ru");
request.getSession().removeAttribute("ru");
if(ru == null) {
response.sendRedirect(request.getContextPath() + "/user/test");
} else {
response.sendRedirect(ru);
}
}
}
</span>


认证的类:

<span style="font-size:18px;">package com.plateno.interceptor;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

public class TerryAuthenticationProvider implements AuthenticationProvider {

@SuppressWarnings("serial")
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
String username = auth.getPrincipal().toString();
String password = auth.getCredentials().toString();
if("user".equals(username) && "user".equals(password)) {
List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("AUTH_ADMIN");
list.add(authority);
System.out.println("authenticate");
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username,password,list);
return authentication;
} else {
throw new AuthenticationException("error:用户名或者密码错误") {
};
}

}

@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}

}
</span>


认证前记录访问的url,认证成功后可以调到访问前的地址:

<span style="font-size:18px;">package com.plateno.interceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;

@SuppressWarnings("deprecation")
public class TerryLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

@Override
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
String returnUrl = buildHttpReturnUrlForRequest(request);
request.getSession().setAttribute("ru", returnUrl);
super.commence(request, response, authException);
}

protected String buildHttpReturnUrlForRequest(HttpServletRequest request)
throws IOException, ServletException {
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme(request.getScheme());
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(request.getServerPort());
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setServletPath(request.getServletPath());
urlBuilder.setPathInfo(request.getPathInfo());
urlBuilder.setQuery(request.getQueryString());
return urlBuilder.getUrl();
}

}
</span>


大体就这样,算作入门。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: