repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/49.Spring-Boot-Async/src/main/java/com/example/demo/DemoApplication.java | 49.Spring-Boot-Async/src/main/java/com/example/demo/DemoApplication.java | package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/49.Spring-Boot-Async/src/main/java/com/example/demo/controller/TestController.java | 49.Spring-Boot-Async/src/main/java/com/example/demo/controller/TestController.java | package com.example.demo.controller;
import com.example.demo.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author MrBird
*/
@RestController
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private TestService testService;
@GetMapping("async")
public String testAsync() throws Exception {
long start = System.currentTimeMillis();
logger.info("异步方法开始");
Future<String> stringFuture = testService.asyncMethod();
String result = stringFuture.get(60, TimeUnit.SECONDS);
logger.info("异步方法返回值:{}", result);
logger.info("异步方法结束");
long end = System.currentTimeMillis();
logger.info("总耗时:{} ms", end - start);
return stringFuture.get();
}
@GetMapping("sync")
public void testSync() {
long start = System.currentTimeMillis();
logger.info("同步方法开始");
testService.syncMethod();
logger.info("同步方法结束");
long end = System.currentTimeMillis();
logger.info("总耗时:{} ms", end - start);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/49.Spring-Boot-Async/src/main/java/com/example/demo/service/TestService.java | 49.Spring-Boot-Async/src/main/java/com/example/demo/service/TestService.java | package com.example.demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @author MrBird
*/
@Service
public class TestService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Async("asyncThreadPoolTaskExecutor")
// @Async
public Future<String> asyncMethod() {
sleep();
logger.info("异步方法内部线程名称:{}", Thread.currentThread().getName());
return new AsyncResult<>("hello async");
}
public void syncMethod() {
sleep();
}
private void sleep() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/49.Spring-Boot-Async/src/main/java/com/example/demo/config/AsyncPoolConfig.java | 49.Spring-Boot-Async/src/main/java/com/example/demo/config/AsyncPoolConfig.java | package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author MrBird
*/
@Configuration
public class AsyncPoolConfig {
@Bean
public ThreadPoolTaskExecutor asyncThreadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(200);
executor.setQueueCapacity(25);
executor.setKeepAliveSeconds(200);
executor.setThreadNamePrefix("asyncThread");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/73.spring-batch-launcher/src/main/java/cc/mrbird/batch/SpringBatchLauncherApplication.java | 73.spring-batch-launcher/src/main/java/cc/mrbird/batch/SpringBatchLauncherApplication.java | package cc.mrbird.batch;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchLauncherApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBatchLauncherApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/73.spring-batch-launcher/src/main/java/cc/mrbird/batch/controller/JobController.java | 73.spring-batch-launcher/src/main/java/cc/mrbird/batch/controller/JobController.java | package cc.mrbird.batch.controller;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author MrBird
*/
@RestController
@RequestMapping("job")
public class JobController {
@Autowired
private Job job;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobOperator jobOperator;
@GetMapping("launcher/{message}")
public String launcher(@PathVariable String message) throws Exception {
JobParameters parameters = new JobParametersBuilder()
.addString("message", message)
.toJobParameters();
// 将参数传递给任务
jobLauncher.run(job, parameters);
return "success";
}
@GetMapping("operator/{message}")
public String operator(@PathVariable String message) throws Exception {
// 传递任务名称,参数使用 kv方式
jobOperator.start("job", "message=" + message);
return "success";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/73.spring-batch-launcher/src/main/java/cc/mrbird/batch/configure/JobConfigure.java | 73.spring-batch-launcher/src/main/java/cc/mrbird/batch/configure/JobConfigure.java | package cc.mrbird.batch.configure;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author MrBird
*/
@Configuration
public class JobConfigure {
/**
* 注册JobRegistryBeanPostProcessor bean
* 用于将任务名称和实际的任务关联起来
*/
@Bean
public JobRegistryBeanPostProcessor processor(JobRegistry jobRegistry, ApplicationContext applicationContext) {
JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor();
postProcessor.setJobRegistry(jobRegistry);
postProcessor.setBeanFactory(applicationContext.getAutowireCapableBeanFactory());
return postProcessor;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/73.spring-batch-launcher/src/main/java/cc/mrbird/batch/job/MyJob.java | 73.spring-batch-launcher/src/main/java/cc/mrbird/batch/job/MyJob.java | package cc.mrbird.batch.job;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author MrBird
*/
@Component
public class MyJob{
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job job(){
return jobBuilderFactory.get("job")
.start(step())
.build();
}
private Step step(){
return stepBuilderFactory.get("step")
.tasklet((stepContribution, chunkContext) -> {
StepExecution stepExecution = chunkContext.getStepContext().getStepExecution();
Map<String, JobParameter> parameters = stepExecution.getJobParameters().getParameters();
System.out.println(parameters.get("message").getValue());
return RepeatStatus.FINISHED;
})
.listener(this)
.build();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/34.Start-Spring-Security/src/main/java/cc/mrbird/SecurityApplication.java | 34.Start-Spring-Security/src/main/java/cc/mrbird/SecurityApplication.java | package cc.mrbird;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/34.Start-Spring-Security/src/main/java/cc/mrbird/security/browser/BrowserSecurityConfig.java | 34.Start-Spring-Security/src/main/java/cc/mrbird/security/browser/BrowserSecurityConfig.java | package cc.mrbird.security.browser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单登录
// http.httpBasic() // HTTP Basic
.and()
.authorizeRequests() // 授权配置
.anyRequest() // 所有请求
.authenticated(); // 都需要认证
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/34.Start-Spring-Security/src/main/java/cc/mrbird/web/controller/TestController.java | 34.Start-Spring-Security/src/main/java/cc/mrbird/web/controller/TestController.java | package cc.mrbird.web.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("hello")
public String hello() {
return "hello spring security";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/Application.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/controller/LoginController.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/controller/LoginController.java | package com.springboot.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.pojo.ResponseBo;
import com.springboot.pojo.User;
import com.springboot.util.MD5Utils;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password, Boolean rememberMe) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!");
}
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@GetMapping("/403")
public String forbid() {
return "403";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/controller/UserController.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/controller/UserController.java | package com.springboot.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequiresPermissions("user:user")
@RequestMapping("list")
public String userList(Model model) {
model.addAttribute("value", "获取用户信息");
return "user";
}
@RequiresPermissions("user:add")
@RequestMapping("add")
public String userAdd(Model model) {
model.addAttribute("value", "新增用户");
return "user";
}
@RequiresPermissions("user:delete")
@RequestMapping("delete")
public String userDelete(Model model) {
model.addAttribute("value", "删除用户");
return "user";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/shiro/ShiroRealm.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/shiro/ShiroRealm.java | package com.springboot.shiro;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.dao.UserMapper;
import com.springboot.dao.UserPermissionMapper;
import com.springboot.dao.UserRoleMapper;
import com.springboot.pojo.Permission;
import com.springboot.pojo.Role;
import com.springboot.pojo.User;
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private UserPermissionMapper userPermissionMapper;
/**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUserName();
System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
List<Role> roleList = userRoleMapper.findByUserName(userName);
Set<String> roleSet = new HashSet<String>();
for (Role r : roleList) {
roleSet.add(r.getName());
}
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
Set<String> permissionSet = new HashSet<String>();
for (Permission p : permissionList) {
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
/**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserRoleMapper.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserRoleMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Role;
@Mapper
public interface UserRoleMapper {
List<Role> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserMapper.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserMapper.java | package com.springboot.dao;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.User;
@Mapper
public interface UserMapper {
User findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserPermissionMapper.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/dao/UserPermissionMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Permission;
@Mapper
public interface UserPermissionMapper {
List<Permission> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/util/MD5Utils.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/util/MD5Utils.java | package com.springboot.util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
public class MD5Utils {
private static final String SALT = "mrbird";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
return newPassword;
}
public static String encrypt(String username, String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
HASH_ITERATIONS).toHex();
return newPassword;
}
public static void main(String[] args) {
System.out.println(MD5Utils.encrypt("tester", "123456"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/ResponseBo.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/ResponseBo.java | package com.springboot.pojo;
import java.util.HashMap;
import java.util.Map;
public class ResponseBo extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public ResponseBo() {
put("code", 0);
put("msg", "操作成功");
}
public static ResponseBo error() {
return error(1, "操作失败");
}
public static ResponseBo error(String msg) {
return error(500, msg);
}
public static ResponseBo error(int code, String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("code", code);
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(Map<String, Object> map) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.putAll(map);
return ResponseBo;
}
public static ResponseBo ok() {
return new ResponseBo();
}
@Override
public ResponseBo put(String key, Object value) {
super.put(key, value);
return this;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/Permission.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/Permission.java | package com.springboot.pojo;
import java.io.Serializable;
public class Permission implements Serializable{
private static final long serialVersionUID = 7160557680614732403L;
private Integer id;
private String url;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/Role.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/Role.java | package com.springboot.pojo;
import java.io.Serializable;
public class Role implements Serializable{
private static final long serialVersionUID = -227437593919820521L;
private Integer id;
private String name;
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/User.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/pojo/User.java | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = -5440372534300871944L;
private Integer id;
private String userName;
private String password;
private Date createTime;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer 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 Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/config/ShiroConfig.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/config/ShiroConfig.java | package com.springboot.config;
import java.util.LinkedHashMap;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import com.springboot.shiro.ShiroRealm;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge(86400);
return cookie;
}
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | 13.Spring-Boot-Shiro-Authorization/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | package com.springboot.handler;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
@ExceptionHandler(value = AuthorizationException.class)
public String handleAuthorizationException() {
return "403";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/DemoApplication.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/DemoApplication.java | package com.example.demo;
import com.example.demo.properties.SystemProperties;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
*
* @author MrBird
*/
@SpringBootApplication
@EnableConfigurationProperties(SystemProperties.class)
public class DemoApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(DemoApplication.class)
.bannerMode(Banner.Mode.OFF)
.run(args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/controller/LoginController.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/controller/LoginController.java | package com.example.demo.controller;
import com.example.demo.authentication.JWTUtil;
import com.example.demo.domain.Response;
import com.example.demo.domain.User;
import com.example.demo.exception.SystemException;
import com.example.demo.properties.SystemProperties;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.SystemUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;
/**
* @author MrBird
*/
@RestController
@Validated
public class LoginController {
@Autowired
private SystemProperties properties;
@PostMapping("/login")
public Response login(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password, HttpServletRequest request) throws Exception {
username = StringUtils.lowerCase(username);
password = MD5Util.encrypt(username, password);
final String errorMessage = "用户名或密码错误";
User user = SystemUtils.getUser(username);
if (user == null)
throw new SystemException(errorMessage);
if (!StringUtils.equals(user.getPassword(), password))
throw new SystemException(errorMessage);
// 生成 Token
String token = JWTUtil.sign(username, password);
Map<String, Object> userInfo = this.generateUserInfo(token, user);
return new Response().message("认证成功").data(userInfo);
}
/**
* 生成前端需要的用户信息,包括:
* 1. token
* 2. user
*
* @param token token
* @param user 用户信息
* @return UserInfo
*/
private Map<String, Object> generateUserInfo(String token, User user) {
String username = user.getUsername();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("token", token);
user.setPassword("it's a secret");
userInfo.put("user", user);
return userInfo;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/controller/TestController.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/controller/TestController.java | package com.example.demo.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author MrBird
*/
@RestController
@RequestMapping("test")
public class TestController {
/**
* 需要登录才能访问
*/
@GetMapping("/1")
public String test1() {
return "success";
}
/**
* 需要 admin 角色才能访问
*/
@GetMapping("/2")
@RequiresRoles("admin")
public String test2() {
return "success";
}
/**
* 需要 "user:add" 权限才能访问
*/
@GetMapping("/3")
@RequiresPermissions("user:add")
public String test3() {
return "success";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTUtil.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTUtil.java | package com.example.demo.authentication;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.properties.SystemProperties;
import com.example.demo.utils.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
*
* @author MrBird
*/
public class JWTUtil {
private static Logger log = LoggerFactory.getLogger(JWTUtil.class);
private static final long EXPIRE_TIME = SpringContextUtil.getBean(SystemProperties.class).getJwtTimeOut() * 1000;
/**
* 校验 token是否正确
*
* @param token 密钥
* @param secret 用户的密码
* @return 是否正确
*/
public static boolean verify(String token, String username, String secret) {
try {
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
verifier.verify(token);
log.info("token is valid");
return true;
} catch (Exception e) {
log.info("token is invalid{}", e.getMessage());
return false;
}
}
/**
* 从 token中获取用户名
*
* @return token中包含的用户名
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
log.error("error:{}", e.getMessage());
return null;
}
}
/**
* 生成 token
*
* @param username 用户名
* @param secret 用户的密码
* @return token
*/
public static String sign(String username, String secret) {
try {
username = StringUtils.lowerCase(username);
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
return JWT.create()
.withClaim("username", username)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
log.error("error:{}", e);
return null;
}
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/ShiroConfig.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/ShiroConfig.java | package com.example.demo.authentication;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
/**
* Shiro 配置类
*
* @author MrBird
*/
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 设置 securityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 在 Shiro过滤器链上加入 JWTFilter
LinkedHashMap<String, Filter> filters = new LinkedHashMap<>();
filters.put("jwt", new JWTFilter());
shiroFilterFactoryBean.setFilters(filters);
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 所有请求都要经过 jwt过滤器
filterChainDefinitionMap.put("/**", "jwt");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 配置 SecurityManager,并注入 shiroRealm
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public ShiroRealm shiroRealm() {
// 配置 Realm
return new ShiroRealm();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/ShiroRealm.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/ShiroRealm.java | package com.example.demo.authentication;
import com.example.demo.domain.User;
import com.example.demo.utils.SystemUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 自定义实现 ShiroRealm,包含认证和授权两大模块
*
* @author MrBird
*/
public class ShiroRealm extends AuthorizingRealm {
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* `
* 授权模块,获取用户角色和权限
*
* @param token token
* @return AuthorizationInfo 权限信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) {
String username = JWTUtil.getUsername(token.toString());
User user = SystemUtils.getUser(username);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集(模拟值,实际从数据库获取)
simpleAuthorizationInfo.setRoles(user.getRole());
// 获取用户权限集(模拟值,实际从数据库获取)
simpleAuthorizationInfo.setStringPermissions(user.getPermission());
return simpleAuthorizationInfo;
}
/**
* 用户认证
*
* @param authenticationToken 身份认证 token
* @return AuthenticationInfo 身份认证信息
* @throws AuthenticationException 认证相关异常
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 这里的 token是从 JWTFilter 的 executeLogin 方法传递过来的,已经经过了解密
String token = (String) authenticationToken.getCredentials();
String username = JWTUtil.getUsername(token);
if (StringUtils.isBlank(username))
throw new AuthenticationException("token校验不通过");
// 通过用户名查询用户信息
User user = SystemUtils.getUser(username);
if (user == null)
throw new AuthenticationException("用户名或密码错误");
if (!JWTUtil.verify(token, username, user.getPassword()))
throw new AuthenticationException("token校验不通过");
return new SimpleAuthenticationInfo(token, token, "shiro_realm");
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTToken.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTToken.java | package com.example.demo.authentication;
import org.apache.shiro.authc.AuthenticationToken;
/**
* JSON Web Token
*
* @author MrBird
*/
public class JWTToken implements AuthenticationToken {
private static final long serialVersionUID = 1282057025599826155L;
private String token;
private String exipreAt;
public JWTToken(String token) {
this.token = token;
}
public JWTToken(String token, String exipreAt) {
this.token = token;
this.exipreAt = exipreAt;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getExipreAt() {
return exipreAt;
}
public void setExipreAt(String exipreAt) {
this.exipreAt = exipreAt;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTFilter.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/authentication/JWTFilter.java | package com.example.demo.authentication;
import com.example.demo.properties.SystemProperties;
import com.example.demo.utils.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author MrBird
*/
public class JWTFilter extends BasicHttpAuthenticationFilter {
private Logger log = LoggerFactory.getLogger(this.getClass());
private static final String TOKEN = "Token";
private AntPathMatcher pathMatcher = new AntPathMatcher();
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
SystemProperties properties = SpringContextUtil.getBean(SystemProperties.class);
String[] anonUrl = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");
boolean match = false;
for (String u : anonUrl) {
if (pathMatcher.match(u, httpServletRequest.getRequestURI()))
match = true;
}
if (match) return true;
if (isLoginAttempt(request, response)) {
return executeLogin(request, response);
}
return false;
}
@Override
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
HttpServletRequest req = (HttpServletRequest) request;
String token = req.getHeader(TOKEN);
return token != null;
}
@Override
protected boolean executeLogin(ServletRequest request, ServletResponse response) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String token = httpServletRequest.getHeader(TOKEN);
JWTToken jwtToken = new JWTToken(token);
try {
getSubject(request, response).login(jwtToken);
return true;
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
/**
* 对跨域提供支持
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
// 跨域时会首先发送一个 option请求,这里我们给 option请求直接返回正常状态
if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
httpServletResponse.setStatus(HttpStatus.OK.value());
return false;
}
return super.preHandle(request, response);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/exception/SystemException.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/exception/SystemException.java | package com.example.demo.exception;
/**
* 系统内部异常
*
* @author MrBird
*/
public class SystemException extends Exception {
private static final long serialVersionUID = -994962710559017255L;
public SystemException(String message) {
super(message);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/domain/Response.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/domain/Response.java | package com.example.demo.domain;
import java.util.HashMap;
/**
*
* @author MrBird
*/
public class Response extends HashMap<String, Object> {
private static final long serialVersionUID = -8713837118340960775L;
public Response message(String message) {
this.put("message", message);
return this;
}
public Response data(Object data) {
this.put("data", data);
return this;
}
@Override
public Response put(String key, Object value) {
super.put(key, value);
return this;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/domain/User.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/domain/User.java | package com.example.demo.domain;
import java.io.Serializable;
import java.util.Set;
/**
* @author MrBird
*/
public class User implements Serializable {
private static final long serialVersionUID = -2731598327208972274L;
private String username;
private String password;
private Set<String> role;
private Set<String> permission;
public User(String username, String password, Set<String> role, Set<String> permission) {
this.username = username;
this.password = password;
this.role = role;
this.permission = permission;
}
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 Set<String> getRole() {
return role;
}
public void setRole(Set<String> role) {
this.role = role;
}
public Set<String> getPermission() {
return permission;
}
public void setPermission(Set<String> permission) {
this.permission = permission;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/MD5Util.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/MD5Util.java | package com.example.demo.utils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
/**
*
* @author MrBird
*/
public class MD5Util {
protected MD5Util(){
}
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String password) {
return new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(password), HASH_ITERATIONS).toHex();
}
public static String encrypt(String username, String password) {
return new SimpleHash(ALGORITH_NAME, password, ByteSource.Util.bytes(username.toLowerCase() + password),
HASH_ITERATIONS).toHex();
}
public static void main(String[] args) {
System.out.println(encrypt("scott","123456"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/SystemUtils.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/SystemUtils.java | package com.example.demo.utils;
import com.example.demo.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* 系统工具类
*
* @author MrBird
*/
public class SystemUtils {
private static Logger log = LoggerFactory.getLogger(SystemUtils.class);
/**
* 模拟两个用户
*
* @return List<User>
*/
private static List<User> users() {
List<User> users = new ArrayList<>();
// 模拟两个用户:
// 1. 用户名 admin,密码 123456,角色 admin(管理员),权限 "user:add","user:view"
// 1. 用户名 scott,密码 123456,角色 regist(注册用户),权限 "user:view"
users.add(new User(
"admin",
"bfc62b3f67a4c3e57df84dad8cc48a3b",
new HashSet<>(Collections.singletonList("admin")),
new HashSet<>(Arrays.asList("user:add", "user:view"))));
users.add(new User(
"scott",
"11bd73355c7bbbac151e4e4f943e59be",
new HashSet<>(Collections.singletonList("regist")),
new HashSet<>(Collections.singletonList("user:view"))));
return users;
}
/**
* 获取用户
*
* @param username 用户名
* @return 用户
*/
public static User getUser(String username) {
List<User> users = SystemUtils.users();
return users.stream().filter(user -> StringUtils.equalsIgnoreCase(username, user.getUsername())).findFirst().orElse(null);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/SpringContextUtil.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/SpringContextUtil.java | package com.example.demo.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring Context 工具类
*
* @author MrBird
*
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<?> getType(String name) {
return applicationContext.getType(name);
}
} | java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/DateUtil.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/utils/DateUtil.java | package com.example.demo.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
/**
* 时间工具类
*
* @author MrBird
*/
public class DateUtil {
public static final String FULL_TIME_PATTERN = "yyyyMMddHHmmss";
public static final String FULL_TIME_SPLIT_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String formatFullTime(LocalDateTime localDateTime) {
return formatFullTime(localDateTime, FULL_TIME_PATTERN);
}
public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(dateTimeFormatter);
}
private static String getDateFormat(Date date, String dateFormatType) {
SimpleDateFormat simformat = new SimpleDateFormat(dateFormatType);
return simformat.format(date);
}
public static String formatCSTTime(String date, String format) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Date d = sdf.parse(date);
return DateUtil.getDateFormat(d, format);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/properties/SystemProperties.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/properties/SystemProperties.java | package com.example.demo.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
*
* @author MrBird
*/
@ConfigurationProperties(prefix = "system")
public class SystemProperties {
/**
* 免认证 URL
*/
private String anonUrl;
/**
* token默认有效时间 1天
*/
private Long jwtTimeOut = 86400L;
public String getAnonUrl() {
return anonUrl;
}
public void setAnonUrl(String anonUrl) {
this.anonUrl = anonUrl;
}
public Long getJwtTimeOut() {
return jwtTimeOut;
}
public void setJwtTimeOut(Long jwtTimeOut) {
this.jwtTimeOut = jwtTimeOut;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/runner/PrintRunner.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/runner/PrintRunner.java | package com.example.demo.runner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
/**
* @author MrBird
*/
@Component
public class PrintRunner implements ApplicationRunner {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void run(ApplicationArguments args) {
logger.info("Provided by handsome 帅比裙主,详情见readme.md");
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/handler/GlobalExceptionHandler.java | 62.Spring-Boot-Shiro-JWT/src/main/java/com/example/demo/handler/GlobalExceptionHandler.java | package com.example.demo.handler;
import com.example.demo.domain.Response;
import com.example.demo.exception.SystemException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;
/**
*
* @author MrBird
*/
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Response handleException(Exception e) {
log.error("系统内部异常,异常信息:", e);
return new Response().message("系统内部异常");
}
@ExceptionHandler(value = SystemException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Response handleParamsInvalidException(SystemException e) {
log.error("系统错误:{}", e.getMessage());
return new Response().message(e.getMessage());
}
/**
* 统一处理请求参数校验(实体对象传参)
*
* @param e BindException
* @return FebsResponse
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response validExceptionHandler(BindException e) {
StringBuilder message = new StringBuilder();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError error : fieldErrors) {
message.append(error.getField()).append(error.getDefaultMessage()).append(",");
}
message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
/**
* 统一处理请求参数校验(普通传参)
*
* @param e ConstraintViolationException
* @return FebsResponse
*/
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response handleConstraintViolationException(ConstraintViolationException e) {
StringBuilder message = new StringBuilder();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
Path path = violation.getPropertyPath();
String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
message.append(pathArr[1]).append(violation.getMessage()).append(",");
}
message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleUnauthorizedException(Exception e) {
log.error("权限不足,{}", e.getMessage());
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/Application.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/controller/LoginController.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/controller/LoginController.java | package com.springboot.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.pojo.ResponseBo;
import com.springboot.pojo.User;
import com.springboot.util.MD5Utils;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password, Boolean rememberMe) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!");
}
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@GetMapping("/403")
public String forbid() {
return "403";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/controller/UserController.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/controller/UserController.java | package com.springboot.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequiresPermissions("user:user")
@RequestMapping("list")
public String userList(Model model) {
model.addAttribute("value", "获取用户信息");
return "user";
}
@RequiresPermissions("user:add")
@RequestMapping("add")
public String userAdd(Model model) {
model.addAttribute("value", "新增用户");
return "user";
}
@RequiresPermissions("user:delete")
@RequestMapping("delete")
public String userDelete(Model model) {
model.addAttribute("value", "删除用户");
return "user";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/shiro/ShiroRealm.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/shiro/ShiroRealm.java | package com.springboot.shiro;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.dao.UserMapper;
import com.springboot.dao.UserPermissionMapper;
import com.springboot.dao.UserRoleMapper;
import com.springboot.pojo.Permission;
import com.springboot.pojo.Role;
import com.springboot.pojo.User;
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private UserPermissionMapper userPermissionMapper;
/**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUserName();
System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
List<Role> roleList = userRoleMapper.findByUserName(userName);
Set<String> roleSet = new HashSet<String>();
for (Role r : roleList) {
roleSet.add(r.getName());
}
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
Set<String> permissionSet = new HashSet<String>();
for (Permission p : permissionList) {
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
/**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserRoleMapper.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserRoleMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Role;
@Mapper
public interface UserRoleMapper {
List<Role> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserMapper.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserMapper.java | package com.springboot.dao;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.User;
@Mapper
public interface UserMapper {
User findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserPermissionMapper.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/dao/UserPermissionMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Permission;
@Mapper
public interface UserPermissionMapper {
List<Permission> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/util/MD5Utils.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/util/MD5Utils.java | package com.springboot.util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
public class MD5Utils {
private static final String SALT = "mrbird";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
return newPassword;
}
public static String encrypt(String username, String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
HASH_ITERATIONS).toHex();
return newPassword;
}
public static void main(String[] args) {
System.out.println(MD5Utils.encrypt("tester", "123456"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/ResponseBo.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/ResponseBo.java | package com.springboot.pojo;
import java.util.HashMap;
import java.util.Map;
public class ResponseBo extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public ResponseBo() {
put("code", 0);
put("msg", "操作成功");
}
public static ResponseBo error() {
return error(1, "操作失败");
}
public static ResponseBo error(String msg) {
return error(500, msg);
}
public static ResponseBo error(int code, String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("code", code);
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(Map<String, Object> map) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.putAll(map);
return ResponseBo;
}
public static ResponseBo ok() {
return new ResponseBo();
}
@Override
public ResponseBo put(String key, Object value) {
super.put(key, value);
return this;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/Permission.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/Permission.java | package com.springboot.pojo;
import java.io.Serializable;
public class Permission implements Serializable{
private static final long serialVersionUID = 7160557680614732403L;
private Integer id;
private String url;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/Role.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/Role.java | package com.springboot.pojo;
import java.io.Serializable;
public class Role implements Serializable{
private static final long serialVersionUID = -227437593919820521L;
private Integer id;
private String name;
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/User.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/pojo/User.java | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = -5440372534300871944L;
private Integer id;
private String userName;
private String password;
private Date createTime;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer 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 Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/config/ShiroConfig.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/config/ShiroConfig.java | package com.springboot.config;
import java.util.LinkedHashMap;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import com.springboot.shiro.ShiroRealm;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
@Configuration
public class ShiroConfig {
@Bean
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:config/shiro-ehcache.xml");
return em;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
securityManager.setCacheManager(getEhCacheManager());
return securityManager;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge(86400);
return cookie;
}
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | 16.Spring-Boot-Shiro-Thymeleaf-Tag/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | package com.springboot.handler;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
@ExceptionHandler(value = AuthorizationException.class)
public String handleAuthorizationException() {
return "403";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/Application.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/controller/LoginController.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/controller/LoginController.java | package com.springboot.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.pojo.ResponseBo;
import com.springboot.pojo.User;
import com.springboot.util.MD5Utils;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!");
}
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/shiro/ShiroRealm.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/shiro/ShiroRealm.java | package com.springboot.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.dao.UserMapper;
import com.springboot.pojo.User;
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
/**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
return null;
}
/**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/dao/UserMapper.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/dao/UserMapper.java | package com.springboot.dao;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.User;
@Mapper
public interface UserMapper {
User findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/util/MD5Utils.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/util/MD5Utils.java | package com.springboot.util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
public class MD5Utils {
private static final String SALT = "mrbird";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
return newPassword;
}
public static String encrypt(String username, String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
HASH_ITERATIONS).toHex();
return newPassword;
}
public static void main(String[] args) {
System.out.println(MD5Utils.encrypt("test", "123456"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/pojo/ResponseBo.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/pojo/ResponseBo.java | package com.springboot.pojo;
import java.util.HashMap;
import java.util.Map;
public class ResponseBo extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public ResponseBo() {
put("code", 0);
put("msg", "操作成功");
}
public static ResponseBo error() {
return error(1, "操作失败");
}
public static ResponseBo error(String msg) {
return error(500, msg);
}
public static ResponseBo error(int code, String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("code", code);
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(Map<String, Object> map) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.putAll(map);
return ResponseBo;
}
public static ResponseBo ok() {
return new ResponseBo();
}
@Override
public ResponseBo put(String key, Object value) {
super.put(key, value);
return this;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/pojo/User.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/pojo/User.java | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = -5440372534300871944L;
private Integer id;
private String userName;
private String password;
private Date createTime;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer 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 Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/config/ShiroConfig.java | 11.Spring-Boot-Shiro-Authentication/src/main/java/com/springboot/config/ShiroConfig.java | package com.springboot.config;
import java.util.LinkedHashMap;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.springboot.shiro.ShiroRealm;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
return securityManager;
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/SecurityApplication.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/SecurityApplication.java | package cc.mrbird;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/domain/MyUser.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/domain/MyUser.java | package cc.mrbird.domain;
import java.io.Serializable;
public class MyUser implements Serializable {
private static final long serialVersionUID = 3497935890426858541L;
private String userName;
private String password;
private boolean accountNonExpired = true;
private boolean accountNonLocked= true;
private boolean credentialsNonExpired= true;
private boolean enabled= true;
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 boolean isAccountNonExpired() {
return accountNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/security/browser/BrowserSecurityConfig.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/security/browser/BrowserSecurityConfig.java | package cc.mrbird.security.browser;
import cc.mrbird.handler.MyAuthenticationFailureHandler;
import cc.mrbird.handler.MyAuthenticationSucessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSucessHandler authenticationSucessHandler;
@Autowired
private MyAuthenticationFailureHandler authenticationFailureHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 表单登录
// http.httpBasic() // HTTP Basic
.loginPage("/authentication/require") // 登录跳转 URL
.loginProcessingUrl("/login") // 处理表单登录 URL
.successHandler(authenticationSucessHandler) // 处理登录成功
.failureHandler(authenticationFailureHandler) // 处理登录失败
.and()
.authorizeRequests() // 授权配置
.antMatchers("/authentication/require", "/login.html").permitAll() // 登录跳转 URL 无需认证
.anyRequest() // 所有请求
.authenticated() // 都需要认证
.and().csrf().disable();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/security/browser/UserDetailService.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/security/browser/UserDetailService.java | package cc.mrbird.security.browser;
import cc.mrbird.domain.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
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.password.PasswordEncoder;
@Configuration
public class UserDetailService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 模拟一个用户,替代数据库获取逻辑
MyUser user = new MyUser();
user.setUserName(username);
user.setPassword(this.passwordEncoder.encode("123456"));
// 输出加密后的密码
System.out.println(user.getPassword());
return new User(username, user.getPassword(), user.isEnabled(),
user.isAccountNonExpired(), user.isCredentialsNonExpired(),
user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/handler/MyAuthenticationFailureHandler.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/handler/MyAuthenticationFailureHandler.java | package cc.mrbird.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Autowired
private ObjectMapper mapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(mapper.writeValueAsString(exception.getMessage()));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/handler/MyAuthenticationSucessHandler.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/handler/MyAuthenticationSucessHandler.java | package cc.mrbird.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class MyAuthenticationSucessHandler implements AuthenticationSuccessHandler {
// private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
//
// @Autowired
// private ObjectMapper mapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
// response.setContentType("application/json;charset=utf-8");
// response.getWriter().write(mapper.writeValueAsString(authentication));
// SavedRequest savedRequest = requestCache.getRequest(request, response);
// System.out.println(savedRequest.getRedirectUrl());
// redirectStrategy.sendRedirect(request, response, savedRequest.getRedirectUrl());
redirectStrategy.sendRedirect(request, response, "/index");
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/web/controller/TestController.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/web/controller/TestController.java | package cc.mrbird.web.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("hello")
public String hello() {
return "hello spring security";
}
@GetMapping("index")
public Object index(Authentication authentication) {
// return SecurityContextHolder.getContext().getAuthentication();
return authentication;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/35.Spring-Security-Authentication/src/main/java/cc/mrbird/web/controller/BrowserSecurityController.java | 35.Spring-Security-Authentication/src/main/java/cc/mrbird/web/controller/BrowserSecurityController.java | package cc.mrbird.web.controller;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author MrBird
*/
@RestController
public class BrowserSecurityController {
private RequestCache requestCache = new HttpSessionRequestCache();
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@GetMapping("/authentication/require")
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
String targetUrl = savedRequest.getRedirectUrl();
if (StringUtils.endsWithIgnoreCase(targetUrl, ".html"))
redirectStrategy.sendRedirect(request, response, "/login.html");
}
return "访问的资源需要身份认证!";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/Application.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/Application.java | package com.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/LoginController.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/LoginController.java | package com.springboot.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.pojo.ResponseBo;
import com.springboot.pojo.User;
import com.springboot.util.MD5Utils;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password, Boolean rememberMe) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!");
}
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@GetMapping("/403")
public String forbid() {
return "403";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/SessionController.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/SessionController.java | package com.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.pojo.ResponseBo;
import com.springboot.pojo.UserOnline;
import com.springboot.service.SessionService;
@Controller
@RequestMapping("/online")
public class SessionController {
@Autowired
SessionService sessionService;
@RequestMapping("index")
public String online() {
return "online";
}
@ResponseBody
@RequestMapping("list")
public List<UserOnline> list() {
return sessionService.list();
}
@ResponseBody
@RequestMapping("forceLogout")
public ResponseBo forceLogout(String id) {
try {
sessionService.forceLogout(id);
return ResponseBo.ok();
} catch (Exception e) {
e.printStackTrace();
return ResponseBo.error("踢出用户失败");
}
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/UserController.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/controller/UserController.java | package com.springboot.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequiresPermissions("user:user")
@RequestMapping("list")
public String userList(Model model) {
model.addAttribute("value", "获取用户信息");
return "user";
}
@RequiresPermissions("user:add")
@RequestMapping("add")
public String userAdd(Model model) {
model.addAttribute("value", "新增用户");
return "user";
}
@RequiresPermissions("user:delete")
@RequestMapping("delete")
public String userDelete(Model model) {
model.addAttribute("value", "删除用户");
return "user";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/shiro/ShiroRealm.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/shiro/ShiroRealm.java | package com.springboot.shiro;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.springboot.dao.UserMapper;
import com.springboot.dao.UserPermissionMapper;
import com.springboot.dao.UserRoleMapper;
import com.springboot.pojo.Permission;
import com.springboot.pojo.Role;
import com.springboot.pojo.User;
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Autowired
private UserPermissionMapper userPermissionMapper;
/**
* 获取用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUserName();
System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
List<Role> roleList = userRoleMapper.findByUserName(userName);
Set<String> roleSet = new HashSet<String>();
for (Role r : roleList) {
roleSet.add(r.getName());
}
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
Set<String> permissionSet = new HashSet<String>();
for (Permission p : permissionList) {
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
/**
* 登录认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
User user = userMapper.findByUserName(userName);
if (user == null) {
throw new UnknownAccountException("用户名或密码错误!");
}
if (!password.equals(user.getPassword())) {
throw new IncorrectCredentialsException("用户名或密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserRoleMapper.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserRoleMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Role;
@Mapper
public interface UserRoleMapper {
List<Role> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserMapper.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserMapper.java | package com.springboot.dao;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.User;
@Mapper
public interface UserMapper {
User findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserPermissionMapper.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/dao/UserPermissionMapper.java | package com.springboot.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.springboot.pojo.Permission;
@Mapper
public interface UserPermissionMapper {
List<Permission> findByUserName(String userName);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/util/MD5Utils.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/util/MD5Utils.java | package com.springboot.util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
public class MD5Utils {
private static final String SALT = "mrbird";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
return newPassword;
}
public static String encrypt(String username, String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
HASH_ITERATIONS).toHex();
return newPassword;
}
public static void main(String[] args) {
System.out.println(MD5Utils.encrypt("tester", "123456"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/service/SessionService.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/service/SessionService.java | package com.springboot.service;
import java.util.List;
import com.springboot.pojo.UserOnline;
public interface SessionService {
List<UserOnline> list();
boolean forceLogout(String sessionId);
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/service/impl/SessionServiceImpl.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/service/impl/SessionServiceImpl.java | package com.springboot.service.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.pojo.User;
import com.springboot.pojo.UserOnline;
import com.springboot.service.SessionService;
@Service("sessionService")
public class SessionServiceImpl implements SessionService {
@Autowired
private SessionDAO sessionDAO;
@Override
public List<UserOnline> list() {
List<UserOnline> list = new ArrayList<>();
Collection<Session> sessions = sessionDAO.getActiveSessions();
for (Session session : sessions) {
UserOnline userOnline = new UserOnline();
User user = new User();
SimplePrincipalCollection principalCollection = new SimplePrincipalCollection();
if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
continue;
} else {
principalCollection = (SimplePrincipalCollection) session
.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
user = (User) principalCollection.getPrimaryPrincipal();
userOnline.setUsername(user.getUserName());
userOnline.setUserId(user.getId().toString());
}
userOnline.setId((String) session.getId());
userOnline.setHost(session.getHost());
userOnline.setStartTimestamp(session.getStartTimestamp());
userOnline.setLastAccessTime(session.getLastAccessTime());
Long timeout = session.getTimeout();
if (timeout == 0l) {
userOnline.setStatus("离线");
} else {
userOnline.setStatus("在线");
}
userOnline.setTimeout(timeout);
list.add(userOnline);
}
return list;
}
@Override
public boolean forceLogout(String sessionId) {
Session session = sessionDAO.readSession(sessionId);
session.setTimeout(0);
return true;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/UserOnline.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/UserOnline.java | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class UserOnline implements Serializable{
private static final long serialVersionUID = 3828664348416633856L;
// session id
private String id;
// 用户id
private String userId;
// 用户名称
private String username;
// 用户主机地址
private String host;
// 用户登录时系统IP
private String systemHost;
// 状态
private String status;
// session创建时间
private Date startTimestamp;
// session最后访问时间
private Date lastAccessTime;
// 超时时间
private Long timeout;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSystemHost() {
return systemHost;
}
public void setSystemHost(String systemHost) {
this.systemHost = systemHost;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(Date startTimestamp) {
this.startTimestamp = startTimestamp;
}
public Date getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(Date lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public Long getTimeout() {
return timeout;
}
public void setTimeout(Long timeout) {
this.timeout = timeout;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/ResponseBo.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/ResponseBo.java | package com.springboot.pojo;
import java.util.HashMap;
import java.util.Map;
public class ResponseBo extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public ResponseBo() {
put("code", 0);
put("msg", "操作成功");
}
public static ResponseBo error() {
return error(1, "操作失败");
}
public static ResponseBo error(String msg) {
return error(500, msg);
}
public static ResponseBo error(int code, String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("code", code);
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(Map<String, Object> map) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.putAll(map);
return ResponseBo;
}
public static ResponseBo ok() {
return new ResponseBo();
}
@Override
public ResponseBo put(String key, Object value) {
super.put(key, value);
return this;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/Permission.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/Permission.java | package com.springboot.pojo;
import java.io.Serializable;
public class Permission implements Serializable{
private static final long serialVersionUID = 7160557680614732403L;
private Integer id;
private String url;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/Role.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/Role.java | package com.springboot.pojo;
import java.io.Serializable;
public class Role implements Serializable{
private static final long serialVersionUID = -227437593919820521L;
private Integer id;
private String name;
private String memo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/User.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/pojo/User.java | package com.springboot.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private static final long serialVersionUID = -5440372534300871944L;
private Integer id;
private String userName;
private String password;
private Date createTime;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer 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 Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/config/ShiroConfig.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/config/ShiroConfig.java | package com.springboot.config;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import com.springboot.listener.ShiroSessionListener;
import com.springboot.shiro.ShiroRealm;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
@Configuration
public class ShiroConfig {
@Bean
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:config/shiro-ehcache.xml");
return em;
}
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
securityManager.setCacheManager(getEhCacheManager());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setMaxAge(86400);
return cookie;
}
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
@Bean
public SessionDAO sessionDAO() {
MemorySessionDAO sessionDAO = new MemorySessionDAO();
return sessionDAO;
}
@Bean
public SessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
Collection<SessionListener> listeners = new ArrayList<SessionListener>();
listeners.add(new ShiroSessionListener());
sessionManager.setSessionListeners(listeners);
sessionManager.setSessionDAO(sessionDAO());
return sessionManager;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/handler/GlobalExceptionHandler.java | package com.springboot.handler;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.ExpiredSessionException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {
@ExceptionHandler(value = AuthorizationException.class)
public String handleAuthorizationException() {
return "403";
}
@ExceptionHandler(value = ExpiredSessionException.class )
public String handleExpiredSessionException() {
return "login";
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/listener/ShiroSessionListener.java | 17.Spring-Boot-Shiro-Session/src/main/java/com/springboot/listener/ShiroSessionListener.java | package com.springboot.listener;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
public class ShiroSessionListener implements SessionListener{
private final AtomicInteger sessionCount = new AtomicInteger(0);
@Override
public void onStart(Session session) {
sessionCount.incrementAndGet();
}
@Override
public void onStop(Session session) {
sessionCount.decrementAndGet();
}
@Override
public void onExpiration(Session session) {
sessionCount.decrementAndGet();
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/22.Spring-Boot-Email/src/test/java/com/springboot/demo/DemoApplicationTests.java | 22.Spring-Boot-Email/src/test/java/com/springboot/demo/DemoApplicationTests.java | package com.springboot.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/22.Spring-Boot-Email/src/main/java/com/springboot/demo/DemoApplication.java | 22.Spring-Boot-Email/src/main/java/com/springboot/demo/DemoApplication.java | package com.springboot.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/22.Spring-Boot-Email/src/main/java/com/springboot/demo/controller/EmailController.java | 22.Spring-Boot-Email/src/main/java/com/springboot/demo/controller/EmailController.java | package com.springboot.demo.controller;
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private JavaMailSender jms;
@Value("${spring.mail.username}")
private String from;
@Autowired
private TemplateEngine templateEngine;
@RequestMapping("sendSimpleEmail")
public String sendSimpleEmail() {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo("888888@qq.com"); // 接收地址
message.setSubject("一封简单的邮件"); // 标题
message.setText("使用Spring Boot发送简单邮件。"); // 内容
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
@RequestMapping("sendHtmlEmail")
public String sendHtmlEmail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("888888@qq.com"); // 接收地址
helper.setSubject("一封HTML格式的邮件"); // 标题
// 带HTML格式的内容
StringBuffer sb = new StringBuffer("<p style='color:#42b983'>使用Spring Boot发送HTML格式邮件。</p>");
helper.setText(sb.toString(), true);
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
@RequestMapping("sendAttachmentsMail")
public String sendAttachmentsMail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("888888@qq.com"); // 接收地址
helper.setSubject("一封带附件的邮件"); // 标题
helper.setText("详情参见附件内容!"); // 内容
// 传入附件
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/file/项目文档.docx"));
helper.addAttachment("项目文档.docx", file);
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
@RequestMapping("sendInlineMail")
public String sendInlineMail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("888888@qq.com"); // 接收地址
helper.setSubject("一封带静态资源的邮件"); // 标题
helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容
// 传入附件
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
helper.addInline("img", file);
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
@RequestMapping("sendTemplateEmail")
public String sendTemplateEmail(String code) {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("888888@qq.com"); // 接收地址
helper.setSubject("邮件摸板测试"); // 标题
// 处理邮件模板
Context context = new Context();
context.setVariable("code", code);
String template = templateEngine.process("emailTemplate", context);
helper.setText(template, true);
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/21.Spring-Boot-Actuator/src/test/java/com/springboot/demo/DemoApplicationTests.java | 21.Spring-Boot-Actuator/src/test/java/com/springboot/demo/DemoApplicationTests.java | package com.springboot.demo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/21.Spring-Boot-Actuator/src/main/java/com/springboot/demo/DemoApplication.java | 21.Spring-Boot-Actuator/src/main/java/com/springboot/demo/DemoApplication.java | package com.springboot.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class DemoApplication {
@RequestMapping("/")
String index() {
return "hello spring boot";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/SecurityApplication.java | 63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/SecurityApplication.java | package cc.mrbird.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/controller/UserController.java | 63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/controller/UserController.java | package cc.mrbird.security.controller;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author MrBird
*/
@RestController
public class UserController {
@GetMapping("index")
public Object index(Authentication authentication){
return authentication;
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
wuyouzhuguli/SpringAll | https://github.com/wuyouzhuguli/SpringAll/blob/614d2578d9495acf53cc02f2dee9c6131cc5e51a/63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/service/UserDetailService.java | 63.Spring-Security-OAuth2-Guide/src/main/java/cc/mrbird/security/service/UserDetailService.java | package cc.mrbird.security.service;
import cc.mrbird.security.domain.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.AuthorityUtils;
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.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserDetailService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MyUser user = new MyUser();
user.setUserName(username);
user.setPassword(this.passwordEncoder.encode("123456"));
return new User(username, user.getPassword(), user.isEnabled(),
user.isAccountNonExpired(), user.isCredentialsNonExpired(),
user.isAccountNonLocked(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
| java | MIT | 614d2578d9495acf53cc02f2dee9c6131cc5e51a | 2026-01-04T14:47:19.901108Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.