ssh 配置记录
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd" default-autowire="byName">
<!-- <debug /> -->
<!-- <global-method-security pre-post-annotations="enabled" /> -->
<http pattern="/**/*.css" security="none"/>
<http pattern="/**/*.js" security="none"/>
<http pattern="/**/*.jpg" security="none"/>
<http pattern="/**/*.png" security="none"/>
<http pattern="/**/*.gif" security="none"/>
<http pattern="/**/*.html" security="none"/>
<http auto-config="true" use-expressions="true" access-denied-page="/noAuthority.jsp">
<!-- <intercept-url pattern="/secure/extreme/**" access="hasRole('supervisor')"/>
<intercept-url pattern="/secure/**" access="isAuthenticated()" /> -->
<!--
Allow all other requests. In a real application you should
adopt a whitelisting approach where access is not allowed by default
-->
<intercept-url pattern="/service/*" access="permitAll" />
<intercept-url pattern="/partial/*" access="permitAll" />
<intercept-url pattern="/echo.jsp" access="permitAll" />
<intercept-url pattern="/randomcode*" access="permitAll" />
<intercept-url pattern="/page/question.jsp" access="permitAll" />
<!-- <intercept-url pattern="/**" access="isAuthenticated()" /> -->
<intercept-url pattern="/**" access="hasRole('ROLE_actived')" />
<form-login login-page="/home_homeLogin.do" authentication-failure-url="/home_homeLogin.do?login_error=1" default-target-url="/home_home.do"
authentication-success-handler-ref="loginAuthenticationSuccessHandler" always-use-default-target="true"/>
<http-basic/>
<logout invalidate-session="true" success-handler-ref="logoutSuccessHandler"/>
<!-- delete-cookies="JSESSIONID" -->
<!-- <remember-me token-validity-seconds="2592000" key="union" user-service-ref="userService" /> -->
<!-- Uncomment to limit the number of sessions a user can have -->
<session-management invalid-session-url="/timeout.jsp" session-fixation-protection="migrateSession" >
</session-management>
<custom-filter ref="stringcheckcodeInterceptor" before="FORM_LOGIN_FILTER"/>
<!-- <custom-filter ref="myFilterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/> -->
</http>
<authentication-manager alias="myAuthenticationManager" erase-credentials="false">
<authentication-provider ref="myAuthenicationProvider" >
</authentication-provider>
</authentication-manager>
<beans:bean id="myAuthenicationProvider" ref="userService"></beans:property>
<beans:property name="hideUserNotFoundExceptions" value="false"></beans:property><!-- false 提示用户不存在 -->
<beans:property name="passwordEncoder" ref="myPasswordEncoder"></beans:property>
<beans:property name="messageSource" ref="messageSource" />
</beans:bean>
<beans:bean id="myPasswordEncoder" ref="myAuthenticationManager"/>
<beans:property name="accessDecisionManager" ref="myAccessDecisionManager">
<!-- <beans:bean
value="false"></beans:property>
<beans:property name="decisionVoters">
<beans:list>
<beans:bean />
RoleVoter默认角色名称都要以ROLE_开头,否则不会被计入权限控制,如果要修改前缀,可以通过对rolePrefix属性进行修改
<beans:bean />
</beans:list>
</beans:property>
</beans:bean> -->
</beans:property>
<beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />
</beans:bean>
<beans:bean id="myAccessDecisionManager" >
</beans:bean>
<beans:bean id="mySecurityMetadataSource" init-method="init">
<beans:property name="roleService" ref="roleService"></beans:property>
</beans:bean>
<beans:bean id="loginAuthenticationFailureHandler" value="true"></beans:property>
</beans:bean>
<beans:bean id="logoutSuccessHandler" value="/home.do?logout=1" >
</beans:property>
</beans:bean>
<beans:bean id="stringcheckcodeInterceptor" value="classpath:resources/springsecurity/messages_zh_CN"/>
</beans:bean>
</beans:beans>
public class AccessDecisionManager extends AbstractAccessDecisionManager{
@Override
public void afterPropertiesSet() throws Exception {
//do nothing
}
@Override
public void decide(Authentication authentication, Object arg1,
Collection<ConfigAttribute> configAttributes) throws AccessDeniedException,
InsufficientAuthenticationException {
if(configAttributes == null)return;
for (ConfigAttribute attribute : configAttributes) {
String needRole = attribute.getAttribute();
for (GrantedAuthority ga : authentication.getAuthorities()) {
if(needRole.equals(ga.getAuthority())){
return;
}
}
}
throw new AccessDeniedException("");
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
@Override
public boolean supports(ConfigAttribute arg0) {
return true;
}
}
public class FilterSecurityInterceptor extends AbstractSecurityInterceptor
implements Filter {
private static final Logger logger = Logger
.getLogger(FilterSecurityInterceptor.class);
private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - start"); //$NON-NLS-1$
}
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
if (logger.isDebugEnabled()) {
logger.debug("doFilter(ServletRequest, ServletResponse, FilterChain) - end"); //$NON-NLS-1$
}
}
public void invoke(FilterInvocation fi) throws IOException,
ServletException {
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return securityMetadataSource;
}
public void setSecurityMetadataSource(
FilterInvocationSecurityMetadataSource securityMetadataSource) {
this.securityMetadataSource = securityMetadataSource;
}
}
public class InvocationSecurityMetadataSource implements
FilterInvocationSecurityMetadataSource {
private static final Logger logger = Logger
.getLogger(InvocationSecurityMetadataSource.class);
private RoleService<Role, Long> roleService;
public RoleService<Role, Long> getRoleService() {
return roleService;
}
public void setRoleService(RoleService<Role, Long> roleService) {
this.roleService = roleService;
}
private final Map<String, Collection<ConfigAttribute>> urlMap;
public InvocationSecurityMetadataSource() {
super();
urlMap = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
}
public void init(){
loadResourceDefine();
}
private void loadResourceDefine() {
List<Role> roles = roleService.getRolesWithPermissions();
if (roles != null && !roles.isEmpty()) {
for (Role role : roles) {
ConfigAttribute ca = new SecurityConfig(role.getName());
Set<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) {
String url = permission.getUrl();
if (urlMap.containsKey(url)) {
Collection<ConfigAttribute> value = urlMap.get(url);
value.add(ca);
urlMap.put(url, value);
} else {
Collection<ConfigAttribute> atts = new LinkedHashSet<ConfigAttribute>();
atts.add(ca);
urlMap.put(url, atts);
}
}
}
}
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
Set<ConfigAttribute> set = new LinkedHashSet<ConfigAttribute>();
for (Collection<ConfigAttribute> collection : urlMap.values()) {
set.addAll(collection);
}
return set;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object)
throws IllegalArgumentException {
if (logger.isDebugEnabled()) {
logger.debug("getAttributes(Object) - start"); //$NON-NLS-1$
}
HttpServletRequest req = ((FilterInvocation) object).getHttpRequest();
String url = req.getServletPath();
if(!StringUtils.isEmpty(req.getQueryString())){
StringBuilder sb = new StringBuilder(url);
sb.append("?");
sb.append(req.getQueryString());
url = sb.toString();
}
Iterator<String> ite = urlMap.keySet().iterator();
while (ite.hasNext()) {
String defURL = ite.next();//定义的权限相关的url
if (url.matches(defURL)) {
Collection<ConfigAttribute> returnCollection = urlMap
.get(defURL);
if (logger.isDebugEnabled()) {
logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$
}
return returnCollection;
}
}
if (logger.isDebugEnabled()) {
logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$
}
return null;
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
private static String defaultFailureUrl = "//home_homeLogin.do?login_error=1" ;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
redirectStrategy.sendRedirect(request, response, defaultFailureUrl);
}
}
public class PasswordEncoder implements org.springframework.security.authentication.encoding.PasswordEncoder{
ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(256);
private final String salt = "111";
@Override
public String encodePassword(String rawPass, Object salt) {
return shaPasswordEncoder.encodePassword(rawPass, this.salt);
}
@Override
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
return shaPasswordEncoder.isPasswordValid(encPass, rawPass, this.salt);
}
}
public class StringCheckCodeInterceptor extends HttpServlet implements Filter{
private final String defaultFailureUrl = "/home_homeLogin.do?login_error=1" ;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
String checkcode = req.getParameter("j_checkcode");
String scheckcode = null;
HttpSession session = request.getSession(false);
if(session == null){
session = request.getSession(true);
}
if(session.getAttribute("j_checkcode_login") != null){
scheckcode = (String) session.getAttribute("j_checkcode_login");
}
if(req.getParameter("needcheckcode_login") != null){
if(StringUtils.isEmpty(scheckcode) || StringUtils.isEmpty(checkcode)){
session.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new RuntimeException("请填写验证码"));
redirectStrategy.sendRedirect(request, (HttpServletResponse)res, defaultFailureUrl);
} else if(scheckcode.equalsIgnoreCase(checkcode)){
chain.doFilter(req, res);
} else {
session.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new RuntimeException("验证码错误"));
redirectStrategy.sendRedirect(request, (HttpServletResponse)res, defaultFailureUrl);
}
return;
}
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}