SpringSecurity用法简介SSM篇——小白专用,大神请绕道

废话不说,直接上代码:

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">

	<context:component-scan base-package="com.atguigu.security"></context:component-scan>

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="username" value="root"></property>
		<property name="password" value="123456"></property>
		<property name="url"
			value="jdbc:mysql://localhost:3306/security?useSSL=false"></property>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	</bean> 
	<!-- jdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:default-servlet-handler />

</beans>

上图是很简单的一段spring-mvc的配置,没什么可说的,有问题的可以留言。

再配置web-xml

<?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"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

	<!-- The front controller of this Spring Web application, responsible for 
		handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</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>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- springSecurity 拦截 -->
	<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>
</web-app>

也是比较中规中矩的配置,都有注释,不想再多bb。

下面菜来了:

先写一个认证登录的方法,需要实现 UserDetailsService 这个接口面试官有时候会问,不知道有什么问的

package com.atguigu.security.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import com.atguigu.security.entity.Admin;

/**
 * 认证相关 连接数据库
 * 
 * @author Administrator
 *
 */
@Component
public class MyUserDetailsService implements UserDetailsService {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * username 表单提交的用户名
	 */
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		// 1.从数据库查询Admin对象
		String sql = "SELECT id,loginacct,userpswd,username,email FROM t_admin WHERE loginacct=?";
		List<Admin> adminList = jdbcTemplate.query(sql,
				new BeanPropertyRowMapper<>(Admin.class), username);
		Admin admin = adminList.get(0);
		String userpswd = admin.getUserpswd();
		List<GrantedAuthority> authorities=new ArrayList();
		// 2.给Admin设置角色权限信息必须加前缀ROLE
		authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		authorities.add(new SimpleGrantedAuthority("UPDATE"));
		return new User(username, userpswd, authorities);
	}

}

需要说明的是,整个过程其实就是查询数据库,然后再把用户的权限信息返回的过程。注意User是security.core.userdetails.User 不是实体类。主要是完成这两步,怎么写都行,只要能返回一个User,并且把所要的信息,给返回就行。

重头戏中的重头戏来了:

package com.atguigu.security.config;

import java.io.IOException;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
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;
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

@EnableWebSecurity
@Configuration
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

	/**
	 * 重写父类方法 定义哪些不需要拦截的资源 设置登录的方法以及登录成功后的跳转地址
	 */
	@Override
	protected void configure(HttpSecurity security) throws Exception {
		// super.configure(http); 取消默认规则
		security.authorizeRequests()
				// 对资源进行授权
				.antMatchers("/layui/**", "/index.jsp")
				// 使用 ANT 风格设置要授权的 URL 地 址
				.permitAll()
				// 允许上面使用 ANT 风格设置的全部请求
				// 通过 HttpSecurity 对象设置资源的角色要求
				// 要想访问level1下的资源得有的等级是学徒
				.antMatchers("/level1/**").hasRole("ADMIN")
				.antMatchers("/level2/**").hasRole("大师")
				.antMatchers("/level3/**").hasRole("宗师").anyRequest() // //其他未设置的全部请求
				.authenticated()// 需要认证
				.and().formLogin() // 使用表单形式登录
				.loginPage("/index.jsp") // 指定的登录页面
				// 关于loginPage()方法的特殊说明
				// 指定登录页的同时会影响到:“提交登录表单的地址”、“退出登录地址”、“登录失败地址”
				// /index.jsp GET - the login form 去登录页面
				// /index.jsp POST - process the credentials and if valid
				// authenticate the user 提交登录表单
				// /index.jsp?error GET - redirect here for failed
				// authentication attempts 登录失败
				// /index.jsp?logout GET - redirect here after successfully
				// logging out 退出登录
				// loginProcessingUrl()方法指定了登录地址,就会覆盖loginPage()方法中设置的默认值/index.jsp
				// POST
				.loginProcessingUrl("/do/login.html") // 指定提交登录表单的地址(即为登录方法)
				.permitAll() // 登录地址也要放行
				.usernameParameter("loginAcct") // 定制登录账号的请求参数名 默认的username 和
												// password
				.passwordParameter("userPswd") // 定制登录密码的请求参数名
				.defaultSuccessUrl("/main.html") // 设置登录成功后默认前往的 URL 地址
				.and().logout() // 开启退出功能
				.logoutUrl("/do/logout.html") // 指定处理退出请求的URL地址
				.logoutSuccessUrl("/index.jsp") // 退出成功后前往的地址
				.and().exceptionHandling()
				// .accessDeniedPage("/to/no/auth/page.html") // 访问被拒绝时前往的页面
				.accessDeniedHandler(new AccessDeniedHandler() {

					@Override
					public void handle(HttpServletRequest request,
							HttpServletResponse response,
							AccessDeniedException accessDeniedException)
							throws IOException, ServletException {
						request.setAttribute("message",
								accessDeniedException.getMessage());
						request.getRequestDispatcher(
								"/WEB-INF/views/no_auth.jsp").forward(request,
								response);

					}
				});
	}

	/**
	 * 认证用户是否正确
	 */
	@Autowired
	private MyUserDetailsService userDetails;
//	@Autowired
//	private MypasswordEncoder passwordEncoder;
	@Bean
	public BCryptPasswordEncoder getPasswordEncoder(){
		return new BCryptPasswordEncoder();
	}
	//使用盐值加密 需要先将盐值的Bean注入到Ioc容器中
	@Override
	protected void configure(AuthenticationManagerBuilder builder)
			throws Exception {
		//内存版
//		builder.inMemoryAuthentication()
//				// 在内存中认证
//				.withUser("tom").password("123123")
//				// 设置账户密码
//				.roles("ADMIN")
//				// 角色
//				.and().withUser("jerry").password("456456")
//				.authorities("SAVE", "EDIT") // 设置权限
//		;
		//TODO 数据库版本
		//调用用户认证方法
		builder.userDetailsService(userDetails)
		//使用加密
		.passwordEncoder(getPasswordEncoder())
		;
	}

}

写一个配置类,继承 WebSecurityConfigurerAdapter ,并重写它的两个同名方法

configure(HttpSecurity security);  configure(AuthenticationManagerBuilder builder);

void configure(HttpSecurity security)这个方法主要是对资源进行管理,放行那些资源,登录成功的跳转路径,什么权限能访问什么资源等等,具体配置代码中配置写到相当清楚,可移驾细看。

void configure(AuthenticationManagerBuilder builder);这个方法是主要进行认证的方法,注意 BCryptPasswordEncoder是用来盐值加密,解密的。之所以加个Bean注解是因为要在容器中能找到。具体代码中有注释,请移嫁。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值