Spring Security的配置

使用和配置spring security,一个基本的权限管理模块

引入这两个包,版本自选,目前是2.5

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${springSecuroty.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${springSecuroty.version}</version>
		</dependency>

新建一个class,目的是配置启动web app时加载spring security

因为是简单配置,所以没有重写里面的任何方法,实际项目中可以根据需求重写里面的方法

package com.demo.config.spring;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityInit extends AbstractSecurityWebApplicationInitializer {

}

具体的spring security权限配置

用户名和密码读取数据库进行鉴权的配置

如下:

package com.demo.config.spring;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private DataSource dataSourceMySQL;

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.jdbcAuthentication()
			.dataSource(dataSourceMySQL)
			.usersByUsernameQuery(this.getUserQuery())
			.authoritiesByUsernameQuery(this.getAuthoritiesQuery());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http
			.csrf() //防止csrf
				.disable()
			.authorizeRequests() //css js的目录设为不需要验证
				.antMatchers("/resources/**")
				.permitAll()
			.anyRequest() //所有请求都要经过验证
				.authenticated()
				.and()
			.formLogin() //登陆页面设为不需要验证
				.loginPage("/login")
				.permitAll()
				.and()
			.logout() //登出请求设为不需要验证
				.permitAll()
				.and()
			.headers() //如果使用iframe的话需要这段配置
				.frameOptions()
				.sameOrigin()
				.httpStrictTransportSecurity()
				.disable(); 
	
	}

	private String getUserQuery() {
		return "SELECT t.user_name as 'username', t.pass_word as 'password', t.enabled as 'enabled' FROM demo.users t WHERE t.user_name = ?";
	}

	private String getAuthoritiesQuery() {
		return "SELECT t.user_name as 'username', t.user_auth as 'authority' FROM demo.authorities t WHERE t.user_name = ?";
	}
	
}

数据库里面有两张表

user表,字段有username,password,enable

authority表,权限等级表,字段有id,username,authority

另外,如果想要根据自己的需求定制登陆登出

新建一个这样的controller:

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class AuthenticationController {
	
	@RequestMapping(value = "/login", produces = "text/html; charset=utf-8")
	public ModelAndView login(HttpServletRequest request){
		return new ModelAndView("loginPage");
	}
	
}

以及一个个性化的登录页面,处理所有的登录和登出:

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Login</title>
</head>
<body>
	<form name="f" action="login" method="post">
		<input type="hidden" name="${_csrf.parameterName}"
			value="${_csrf.token}" />
		<fieldset>
			<c:if test="${param.error != null}">
				<p><span style="color:red;">Invalid username and password.</span></p>
			</c:if>
			<c:if test="${param.logout != null}">
				<p><span style="color:red;">You have been logged out.</span></p>
			</c:if>
			<legend>Please Login</legend>
			<label for="username">Username</label> <input type="text"
				id="username" name="username" /> <label for="password">Password</label>
			<input type="password" id="password" name="password" />
			<div class="form-actions">
				<button type="submit" class="btn">Log in</button>
			</div>
		</fieldset>
	</form>
</body>
</html>

补充:

1. 登陆自动转发请求/login,可以参考前面SecurityConfig.class的代码进行修改。

2. 如果输错密码,会自动转发请求/login?error

3. 登出自动转发请求/login?logout

个性化的页面,加密方式,等等都可以按需定制,spring security很强大的。

配置完成,网站有了全局的权限管理咯

以上

猜你喜欢

转载自neverflyaway.iteye.com/blog/2295226