SpringBoot 下 SpringSecurity 入门搭建

提示:仅供自己学习参考(开发环境maven3.9+jdk1.7+eclipseMar4.5.2)

1、目录结构:


2、源代码:

(1)Springboot001Application 类

package com.ljh.springboot001;

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

@SpringBootApplication
public class Springboot001Application {


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

(2)WebMvcConfig 类继承WebMvcConfigurerAdapter(spring-webmvc-4.1.16.RELEASE.jar的)

package com.ljh.springboot001.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");
}

}

(3)WebSecurityConfig 类继承WebSecurityConfigurerAdapter(spring-security-config-3.2.7.RELEASE.jar的)

package com.ljh.springboot001.config;

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;

import com.ljh.springboot001.security.CustomUserService;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

@Bean
UserDetailsService customUserService(){
System.out.println("userservice ........................");
return new CustomUserService();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll()
.and()
.logout().permitAll();
}
// .defaultSuccessUrl("/home")

}


(4)SysUserRepository接口继承JpaRepository(spring-data-jpa-xxx.jar的)

package com.ljh.springboot001.dao;
 
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;


import com.ljh.springboot001.domain.SysUser;


@Repository
public interface SysUserRepository extends JpaRepository<SysUser, Long>{  
     
SysUser findByUsername(String username);
}  

(5)Msg 类

package com.ljh.springboot001.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;
}

}

(6)SysRole 类

package com.ljh.springboot001.domain;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class SysRole {//角色 即 权限
@Id
@GeneratedValue
private Long id;

private String name;
    
public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}

}


(7)SysUser  类实现UserDetails   接口(spring-security-core-xxx.jar)

package com.ljh.springboot001.domain;


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

import javax.annotation.Generated;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;


import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


@Entity
public class SysUser  implements UserDetails   { //用户


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

@ManyToMany(cascade = {CascadeType.REFRESH},fetch = FetchType.EAGER)
private List<SysRole> roles ;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
List<SysRole> roles = this.getRoles();
for (SysRole role : roles) {
auths.add(new SimpleGrantedAuthority(role.getName()));
}
return auths;
}

public List<SysRole> getRoles() {
return roles;
}

public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}


public void setUsername(String username) {
this.username = username;
}


public void setPassword(String password) {
this.password = password;
}


public void setRoles(List<SysRole> roles) {
this.roles = roles;
}




@Override
public String getPassword() {
return password;
}


@Override
public String getUsername() {
return username;
}


@Override
public boolean isAccountNonExpired() {
return true;
}


@Override
public boolean isAccountNonLocked() {
return true;
}


@Override
public boolean isCredentialsNonExpired() {
return true;
}


@Override
public boolean isEnabled() {
return true;
}


}


(8)CustomUserService 类实现UserDetailsService接口(spring-security-core-xxx.jar)

package com.ljh.springboot001.security;


import org.springframework.beans.factory.annotation.Autowired;
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.Service;


import com.ljh.springboot001.dao.SysUserRepository;
import com.ljh.springboot001.domain.SysUser;


public class CustomUserService implements UserDetailsService{
@Autowired
SysUserRepository sysUserRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("loadUserByUsername......................");
SysUser user  = sysUserRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("用户名不存在");
}
return user;
}


}

(9)HomeController 类

package com.ljh.springboot001.web;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


import com.ljh.springboot001.domain.Msg;


@Controller
public class HomeController {


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


(10)bootstrap文件


(11)thymeleaf模板文件


(12)springboot核心配置文件(application.properties)

server.port=9000
#spring.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc\:mysql\:\localhost:3306\test?useUnicode=true&&characterEncoding=utf-8
#spring.datasource.username=root
#spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.password=123456
spring.datasource.username=root
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

logging.level.org.springframework.security=INFO
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html  
#spring.thymeleaf.mode=HTML5  
#spring.thymeleaf.encoding=UTF-8;charset=<encoding> is added 
#spring.thymeleaf.content-type=text/html  
spring.thymeleaf.cache=true
  
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server.tomcat.uri-encoding=utf-8
#spring.mvc.view.prefix=/templates/
#spring.mvc.view.suffix=.html
#内存中的默认用户账号
security.user.name=ljh
#内存中的默认密码
security.user。password=ljh
(13)data.sql文件
 
insert into SYS_USER(id ,username,password) values (1,'ljh','ljh');
insert into SYS_USER(id ,username,password) values (2,'sdd','sdd');
insert into SYS_ROLE(id ,name) values (1,'ROLE_ADMIN');
insert into SYS_ROLE(id ,name) values (2,'ROLE_USER');
insert into SYS_USER_ROLES(SYS_USER_ID ,ROLES_ID) values (1,1);
insert into SYS_USER_ROLES(SYS_USER_ID ,ROLES_ID) values (2,2);

(14)home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta content="text/html;charset=UTF-8"/>
<title sec:authentication="name"></title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/>
<style type="text/css">
body{
padding-top:50px;
}
.starter-template{
padding:40px 15px;
text-align: center;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class = "navbar-header">
<a class = "navbar-brand" href = "#">Spring security demo</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class = "nav navbar-nav">
<li><a th:href="@{/}">首页</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1 th:text="${msg.title}"></h1>
<p class="bg-primary" th:text="${msg.content}"></p>
<div sec:authorize="hasRole('ROLE_ADMIN')"> 
<p class="bg-info" th:text="${msg.etraInfo}"></p>
</div>
<div sec:authorize="hasRole('ROLE_USER')"> 
<p class="bg-info"> 无更多信息显示</p>
</div>
<form th:action="@{/logout}" method="post">
<input type="submit" class="btn btn-primary" value="exit"/>
</form>
</div>
</div>
</body>
</html>
(15)login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head>
<meta content="text/html;charset=UTF-8"></meta>
<title>login  page </title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"/>
<style type="text/css">
body{
padding-top:50px;
}
.starter-template{
padding:40px 15px;
text-align: center;
}
</style>


</head>


<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class = "navbar-header">
<a class = "navbar-brand"  href = "#">Spring security demo</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class = "nav navbar-nav">
<li><a th:href="@{/}">首页</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<p th:if="${param.logout}" class="bg-warning">成功注销</p>
<p th:if="${param.error}" class="bg-danger">有错误,重试1233</p>
</div>
<h2>请登录</h2>
<form name = "form" th:action="@{/login}" action="/login" method="post">
<div class="form-group">
<label for="username">账号</label>
<input type="text" class="form-control" name="username" value="" placeholder="username"/>
</div> 
<div class="form-group">
<label for="password">mima</label>
<input type="password" class="form-control" name="password" value="" placeholder="password"/>
</div> 
<input type="submit" id="login" value="Login"  class="btn btn-primary"/>
</form>
</div>
</body>
</html>


(16)pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>


<groupId>com.ljh</groupId>
<artifactId>springboot001</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>


<name>springboot001</name>
<description>Demo project for Spring Boot</description>


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
    <!-- https://mvnrepository.com/artifact/javax.persistence/persistence-api -->
<!-- <dependency> -->
<!--    <groupId>javax.persistence</groupId> -->
<!--    <artifactId>persistence-api</artifactId> -->
<!--    <version>1.0</version> -->
<!-- </dependency> -->
<dependency>
  <groupId>org.hibernate.javax.persistence</groupId>
  <artifactId>hibernate-jpa-2.0-api</artifactId>
  <version>1.0.1.Final</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
   <version>1.5.6.RELEASE</version>
</dependency>
   
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
   <version>1.5.6.RELEASE</version>
</dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>
       <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity4</artifactId>
   <version>2.1.3.RELEASE</version>
</dependency>
<dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-thymeleaf</artifactId>  
</dependency>  
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/servlet-api -->
<dependency>
   <groupId>org.apache.tomcat</groupId>
   <artifactId>servlet-api</artifactId>
   <version>6.0.39</version>
</dependency>

</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>




</project>


相应的错误解决办法看下篇:http://blog.csdn.net/lijiaheng525/article/details/76916732

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值