SpringSecurity+用户登录验证

SpringSecurity+用户登录验证_第1张图片

----------------
package com.wisely.ch9_1.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
	}

}

----------------
package com.wisely.ch9_1.config;


import com.wisely.ch9_1.security.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {//1

	@Bean
    UserDetailsService customUserService(){ //配置用户
		return new CustomUserService();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//用户认证
 	auth.userDetailsService(customUserService()); //3

	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()//通过authorizeRequests方法来请求权限配置
//						.antMatchers("/admin/**").hasRole("admin")//只有admin的角色才可以访问(不需要认证)
//						.antMatchers("/user/**").hasAnyRole("user","admin")//只有admin或者user角色才可以访问(不需要认证)
						.anyRequest().authenticated() //所有的请求都要认证后才可以访问
						.and()
						.formLogin()//通过formLogin方法定制登录操作
						.loginPage("/login")//登录页面地址
						.failureUrl("/login?error")//登录失败页面
						.permitAll() //5
						.and()
						.rememberMe()//开启cookie存储用户信息
							.tokenValiditySeconds(3600)//cookie有效期为1小时
							.key("cookie")//指定cookie的私钥
						.and()
						.logout()//定制注销
							.logoutUrl("/custom-loginout")//注销的url
							.logoutSuccessUrl("/loginout-success")//注销成功跳转的请求
							.permitAll(); //6
	}


}

----------------
package com.wisely.ch9_1.domain;

public class Msg {
	private String title;
	private String content;
	private String etraInfo;

	public Msg(String title, String content, String etraInfo) {
		super();
		this.title = title;
		this.content = content;
		this.etraInfo = etraInfo;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getEtraInfo() {
		return etraInfo;
	}
	public void setEtraInfo(String etraInfo) {
		this.etraInfo = etraInfo;
	}

}

----------------
package com.wisely.ch9_1.domain;


public class SysRole {
	private Long id;
	private String name;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public SysRole(Long id, String name) {
		this.id = id;
		this.name = name;
	}
}

----------------
package com.wisely.ch9_1.domain;

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


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class SysUser implements UserDetails{ //UserDetails接口作用使我们的SysUser实体为springSecurity所使用的用户

	private static final long serialVersionUID = 1L;
	private Long id;
	private String username;
	private String password;

	public SysUser(Long id, String username, String password, List roles) {
		this.id = id;
		this.username = username;
		this.password = password;
		this.roles = roles;
	}

	private List roles;


	@Override
	public Collection getAuthorities() { //将用户的角色作为权限
		List auths = new ArrayList();
		List roles=this.getRoles();
		for(SysRole role:roles){
			auths.add(new SimpleGrantedAuthority(role.getName()));
		}
		return auths;
	}
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}
	@Override
	public boolean isAccountNonLocked() {
		return true;
	}
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}
	@Override
	public boolean isEnabled() {
		return true;
	}

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public List getRoles() {
		return roles;
	}
	public void setRoles(List roles) {
		this.roles = roles;
	}




}

----------------
package com.wisely.ch9_1.security;


import com.wisely.ch9_1.domain.SysRole;
import com.wisely.ch9_1.domain.SysUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

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

public class CustomUserService implements UserDetailsService { //1

	@Override
	public UserDetails loadUserByUsername(String username) { //2

		SysRole role=new SysRole(1L,"ROLE_USER");
		SysRole role2=new SysRole(2L,"ROLE_ADMIN");
		List roles1=new ArrayList<>();
        List roles2=new ArrayList<>();
        roles1.add(role);
        roles2.add(role2);
		SysUser user =  new SysUser(1L,"u1","1",roles1);
        SysUser user2 =  new SysUser(2L,"u2","1",roles2);
        if(username.equals("u1")){
            return user;
        }else {
            return user2;
        }
	}

}

----------------
package com.wisely.ch9_1.web;


import com.wisely.ch9_1.domain.Msg;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	
	@RequestMapping("/")
	public String index(Model model){
		Msg msg =  new Msg("测试标题","测试内容","额外信息,只对管理员显示");
		model.addAttribute("msg", msg);
		return "home";
	}

}

----------------
package com.wisely.ch9_1;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Ch91Application {

    public static void main(String[] args) {
        SpringApplication.run(Ch91Application.class, args);
    }
}

----------------




 




	 


     

无更多信息显示

---------------- 登录页面

已成功注销

有错误,请重试

使用账号密码登录

---------------- ----------------

测试

SpringSecurity+用户登录验证_第2张图片

SpringSecurity+用户登录验证_第3张图片

u2登录

SpringSecurity+用户登录验证_第4张图片

你可能感兴趣的:(SpringBoot)