// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home", "/test", "/login").permitAll()//某些请求不需要登录->放行某些接口
.anyRequest().authenticated();//其他的接口拦截
http.formLogin();//拦截后跳转到表单页面
}
@RequestMapping("home")
public String home(){
return "test.html";
}
// 认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("user")
.password(new BCryptPasswordEncoder().encode("123456"))
.authorities("user")
.and()
.withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456"))
.authorities("user","admin");//权限->字符串 ->页面(配置权限)
}
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home","/login").permitAll()//某些请求不需要登录->放行某些接口
.antMatchers("/user").hasAuthority("user")//对页面配置权限
.antMatchers("/admin").hasAuthority("admin")
.anyRequest().authenticated();//其他的接口拦截
http.formLogin();//拦截后跳转到表单页面
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>用户页面h1>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1>admin页面h1>
body>
html>
@RequestMapping("user")
public String user(){
return "user.html";
}
@RequestMapping("admin")
public String admin(){
return "admin.html";
}
package com.example.springboot2.utils;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class MyUserService implements UserDetailsService {
// 重写登录逻辑 username->登录页面输入的用户名
// 第一步:数据库user表 字段:id username password
// username去数据库中查询用户(select * from user where username=?)->0、1、多条(注册时->username提示不能重复)
// 第二步:如果是0条->throws UsernameNotFoundException 如果是1条->从用户信息取得密码
// 第三步:用查询出来的密码与用户输入的密码进行比对(框架完成)
// 第四步:根据username 去查询权限roles(id,name) user表roles表多对多->中间表
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String password="123456";//todo 从数据库中查询得到
// user、admin权限 todo 从数据库中查询得到
GrantedAuthority authority1=new SimpleGrantedAuthority("user");
GrantedAuthority authority2=new SimpleGrantedAuthority("admin");
List<GrantedAuthority> list=new ArrayList<>();
if (username.equals("user")){
list.add(authority1);
}
if (username.equals("admin")){
list.add(authority1);
list.add(authority2);
}
return new User(username,new BCryptPasswordEncoder().encode(password),list);
}
}
package com.example.springboot2.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {
// 认证
// 认证->从数据库中获取用户名和密码进行验证
@Autowired
MyUserService myUserService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(myUserService).passwordEncoder(new BCryptPasswordEncoder());
// auth.inMemoryAuthentication()
// .withUser("user")
// .password(new BCryptPasswordEncoder().encode("123456"))
// .authorities("user")
// .and()
// .withUser("admin")
// .password(new BCryptPasswordEncoder().encode("123456"))
// .authorities("user","admin");//权限->字符串 ->页面(配置权限)
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home","/login").permitAll()//某些请求不需要登录->放行某些接口
.antMatchers("/user").hasAuthority("user")//对页面配置权限
.antMatchers("/admin").hasAuthority("admin")
.anyRequest().authenticated();//其他的接口拦截
http.formLogin();//拦截后跳转到表单页面
}
}
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home","/login").permitAll()//某些请求不需要登录->放行某些接口
.antMatchers("/user").hasAuthority("user")//对页面配置权限
.antMatchers("/admin").hasAuthority("admin")
.anyRequest().authenticated();//其他的接口拦截
http.formLogin()//拦截后跳转到表单页面
.loginPage("/login")// /login 自己写的页面->默认需要权限
.loginProcessingUrl("/user/login");//登录提交的请求->框架提供的
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面title>
head>
<body>
<h1>登录页面h1>
<form th:action="@{/user/login}" method="post">
<div>用户名:<input name="username">div>
<div>密码:<input name="password">div>
<div><input type="submit" value="提交">div>
form>
body>
html>
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home","/login").permitAll()//某些请求不需要登录->放行某些接口
.antMatchers("/user").hasAuthority("user")//对页面配置权限
.antMatchers("/admin").hasAuthority("admin")
.anyRequest().authenticated();//其他的接口拦截
http.formLogin()//拦截后跳转到表单页面
.loginPage("/login")// /login 自己写的页面->默认需要权限
.loginProcessingUrl("/user/login")//登录提交的请求->框架提供的
.and()
.logout()
.logoutUrl("/logout");//登录提交的请求
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>退出登录页面title>
head>
<body>
<h1>你确定要退出吗?h1>
<form th:action="@{/logout}" method="post">
<button>退出登录button>
form>
body>
html>
@RequestMapping("mylogout")
public String mylogout(){
return "mylogout.html";
}
spring.web.resources.static-locations=classpath:/templates,file:D:/data/
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form th:action="@{/filecommit}" method="post" enctype="multipart/form-data">
<div>文件名:<input type="file" name="file">div>
<div><input type="submit" value="提交">div>
form>
body>
html>
package com.example.springboot2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Controller
public class FileController {
@RequestMapping("file")
public String file(){
return "file.html";
}
}
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()//拦截所有请求
.antMatchers("/home","/login","/**").permitAll()//某些请求不需要登录->放行某些接口
.antMatchers("/user").hasAuthority("user")//对页面配置权限
.antMatchers("/admin").hasAuthority("admin")
.anyRequest().authenticated();//其他的接口拦截
http.formLogin()//拦截后跳转到表单页面
.loginPage("/login")// /login 自己写的页面->默认需要权限
.loginProcessingUrl("/user/login")//登录提交的请求->框架提供的
.and()
.logout()
.logoutUrl("/logout");//登录提交的请求
}
// 图片、音频、视频一般不直接存数据库 数据库只存文件名字和文件路径
@RequestMapping("filecommit")
public String filecommit(MultipartFile file) throws IOException {
String filedirs="D:/data/";
String filename=file.getOriginalFilename();
file.transferTo(new File(filedirs+filename));
return "success.html";
}
// 图片、音频、视频一般不直接存数据库 数据库只存文件名字和文件路径
@RequestMapping("filecommit")
public String filecommit(MultipartFile file) throws IOException {
String filedirs="D:/data/";
// String filename=file.getOriginalFilename();
String filename= UUID.randomUUID()+file.getOriginalFilename();
file.transferTo(new File(filedirs+filename));
return "success.html";
}
// 图片、音频、视频一般不直接存数据库 数据库只存文件名字和文件路径
@RequestMapping("filecommit")
public String filecommit(MultipartFile file, Model model) throws IOException {
String filedirs="D:/data/";
// String filename=file.getOriginalFilename();
String filename= UUID.randomUUID()+file.getOriginalFilename();
file.transferTo(new File(filedirs+filename));
model.addAttribute("filename",filename);
return "success.html";
}
package com.example.springboot2.pojo;
import lombok.Data;
@Data
public class News {
private int id;
private String title;
private String content;
}
package com.example.springboot2.controller;
import com.example.springboot2.pojo.News;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class JSONController {
// JSON数据->手机Android端/IOS/小程序
@RequestMapping("getnews")
@ResponseBody //返回JSON数据(特殊格式的字符串)
public News getNews(){
News news=new News();
news.setId(1);
news.setTitle("新闻标题");
news.setContent("新闻内容");
return news;
}
}
// JSON接口配置
http.cors();
http.csrf().disable();
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js">script>
head>
<body>
<script>
function getnews(){
// jQuery请求数据
$.ajax({
type:"post",
url:"http://localhost:8080/getnews",
contentType:"application/json",
success:function (res){
console.log(res)
document.getElementById("title").innerText=res.title
document.getElementById("content").innerText=res.content
}
})
}
script>
<div id="title">新闻标题div>
<div id="content">新闻内容div>
<button onclick="getnews()">获取数据button>
body>
html>