Commit 6d23c281 authored by 杨伊博's avatar 杨伊博

spring boot shiro is ok

parent 2cb4b66e
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.us</groupId>
<artifactId>shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
<relativePath></relativePath>
</parent>
<properties>
<start-class>com.unistacks.epp.manager.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<mybatis.version>3.2.7</mybatis.version>
<mybatis-spring.version>1.2.2</mybatis-spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--db-->
<!--shiro相关-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>1.2.1</version>
</dependency>
<!--log4j12-->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.11</artifactId>
<version>0.10.1.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--db-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.us;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import static org.springframework.boot.SpringApplication.run;
/**
* Created by yangyibo on 17/1/17.
*/
@ComponentScan(basePackages ="com.us")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
package com.us.bean;
import java.util.Date;
public class Event {
private Integer id;
private Integer rawEventId;
private String host;
private String ip;
private String source;
private String type;
private Date startTime;
private Date endTime;
private String content;
private String dataType;
private String suggest;
private Integer businessSystemId;
private Integer departmentId;
private String status;
private Integer occurCount;
private String owner;
private Date responsedTime;
private String responsedBy;
private Date resolvedTime;
private String resolvedBy;
private Date closedTime;
private String closedBy;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRawEventId() {
return rawEventId;
}
public void setRawEventId(Integer rawEventId) {
this.rawEventId = rawEventId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getSuggest() {
return suggest;
}
public void setSuggest(String suggest) {
this.suggest = suggest;
}
public Integer getBusinessSystemId() {
return businessSystemId;
}
public void setBusinessSystemId(Integer businessSystemId) {
this.businessSystemId = businessSystemId;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOccurCount() {
return occurCount;
}
public void setOccurCount(Integer occurCount) {
this.occurCount = occurCount;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Date getResponsedTime() {
return responsedTime;
}
public void setResponsedTime(Date responsedTime) {
this.responsedTime = responsedTime;
}
public String getResponsedBy() {
return responsedBy;
}
public void setResponsedBy(String responsedBy) {
this.responsedBy = responsedBy;
}
public Date getResolvedTime() {
return resolvedTime;
}
public void setResolvedTime(Date resolvedTime) {
this.resolvedTime = resolvedTime;
}
public String getResolvedBy() {
return resolvedBy;
}
public void setResolvedBy(String resolvedBy) {
this.resolvedBy = resolvedBy;
}
public Date getClosedTime() {
return closedTime;
}
public void setClosedTime(Date closedTime) {
this.closedTime = closedTime;
}
public String getClosedBy() {
return closedBy;
}
public void setClosedBy(String closedBy) {
this.closedBy = closedBy;
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", rawEventId=" + rawEventId +
", host=" + host +
", ip=" + ip +
", source=" + source +
", type=" + type +
", startTime=" + startTime +
", endTime=" + endTime +
", content=" + content +
", dataType=" + dataType +
", suggest=" + suggest +
", businessSystemId=" + businessSystemId +
", departmentId=" + departmentId +
", status=" + status +
", occurCount=" + occurCount +
", owner=" + owner +
", responsedTime=" + responsedTime +
", responsedBy=" + responsedBy +
", resolvedTime=" + resolvedTime +
", resolvedBy=" + resolvedBy +
", closedTime=" + closedTime +
", closedBy=" + closedBy +
'}';
}
}
\ No newline at end of file
package com.us.bean;
public class Permission {
private Integer id;
private String name;
private String permissionUrl;
private String method;
private String description;
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 getPermissionUrl() {
return permissionUrl;
}
public void setPermissionUrl(String permissionUrl) {
this.permissionUrl = permissionUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Permission{" +
"id=" + id +
", name=" + name +
", permissionUrl=" + permissionUrl +
", method=" + method +
", description=" + description +
'}';
}
}
\ No newline at end of file
package com.us.bean;
public class Role {
private Integer id;
private String name;
private Integer roleLevel;
private String description;
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 Integer getRoleLevel() {
return roleLevel;
}
public void setRoleLevel(Integer roleLevel) {
this.roleLevel = roleLevel;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", name=" + name +
", roleLevel=" + roleLevel +
", description=" + description +
'}';
}
}
\ No newline at end of file
package com.us.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public class User {
private Integer id;
private String cnname;
private String username;
@JsonIgnore
private String password;
private String email;
private String telephone;
private String mobilePhone;
private String wechatId;
private String skill;
private Integer departmentId;
private Integer loginCount;
private List<Role> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCnname() {
return cnname;
}
public void setCnname(String cnname) {
this.cnname = cnname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getWechatId() {
return wechatId;
}
public void setWechatId(String wechatId) {
this.wechatId = wechatId;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public Integer getLoginCount() {
return loginCount;
}
public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
", wechatId=" + wechatId +
", skill=" + skill +
", departmentId=" + departmentId +
", loginCount=" + loginCount +
'}';
}
}
\ No newline at end of file
package com.us.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import java.beans.PropertyVetoException;
@Configuration
public class DataSourceConfig {
@Autowired
private Environment env;
@Bean(name="dataSource")
public ComboPooledDataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
dataSource.setUser(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
dataSource.setMaxPoolSize(20);
dataSource.setMinPoolSize(5);
dataSource.setInitialPoolSize(10);
dataSource.setMaxIdleTime(300);
dataSource.setAcquireIncrement(5);
dataSource.setIdleConnectionTestPeriod(60);
return dataSource;
}
}
package com.us.config;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("**.dao");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
package com.us.config;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(
ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setJdbcTypeForNull(JdbcType.NULL);
sessionFactory.setMapperLocations(applicationContext.getResources("classpath:mapper/*.xml"));
return sessionFactory;
}
}
package com.us.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
@Configuration
public class TransactionConfig implements TransactionManagementConfigurer{
@Autowired
private DataSource dataSource;
@Override
@Bean
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
package com.us.controller;
import com.us.bean.Event;
import com.us.service.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RequestMapping(value = "/events")
@RestController
public class EventController {
@Autowired
private EventService eventService;
@RequestMapping(method = RequestMethod.GET)
public List<Event> list(HttpServletRequest request) {
return eventService.getByMap(null);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Event detail(@PathVariable Integer id) {
return eventService.getById(id);
}
@RequestMapping(method = RequestMethod.POST)
public Event create(@RequestBody Event event) {
return eventService.create(event);
}
@RequestMapping(method = RequestMethod.PUT)
public Event update(@RequestBody Event event) {
return eventService.update(event);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public int delete(@PathVariable Integer id) {
return eventService.delete(id);
}
}
\ No newline at end of file
package com.us.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* Created by cdyoue on 2016/10/21.
* 登陆控制器
*/
@RestController
public class LoginController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(
@RequestParam(value = "username", required = true) String userName,
@RequestParam(value = "password", required = true) String password,
@RequestParam(value = "rememberMe", required = true, defaultValue = "false") boolean rememberMe
) {
logger.info("==========" + userName + password + rememberMe);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
token.setRememberMe(rememberMe);
try {
subject.login(token);
} catch (AuthenticationException e) {
e.printStackTrace();
// rediect.addFlashAttribute("errorText", "您的账号或密码输入错误!");
return "{\"Msg\":\"您的账号或密码输入错误\",\"state\":\"failed\"}";
}
return "{\"Msg\":\"登陆成功\",\"state\":\"success\"}";
}
@RequestMapping("/")
@ResponseBody
public String index() {
return "no permission";
}
}
package com.us.controller;
import com.us.bean.User;
import com.us.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RequestMapping(value = "/users")
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.GET)
public List<User> list(HttpServletRequest request) {
return userService.getByMap(null);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User detail(@PathVariable Integer id) {
return userService.getById(id);
}
@RequestMapping(method = RequestMethod.POST)
public User create(@RequestBody User user) {
return userService.create(user);
}
@RequestMapping(method = RequestMethod.PUT)
public User update(@RequestBody User user) {
return userService.update(user);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public int delete(@PathVariable Integer id) {
return userService.delete(id);
}
}
\ No newline at end of file
package com.us.dao;
import com.us.bean.Event;
import java.util.List;
import java.util.Map;
public interface EventDao {
List<Event> getByMap(Map<String, Object> map);
Event getById(Integer id);
Integer create(Event event);
int update(Event event);
int delete(Integer id);
}
\ No newline at end of file
package com.us.dao;
import com.us.bean.Permission;
import java.util.List;
import java.util.Map;
public interface PermissionDao {
List<Permission> getByMap(Map<String, Object> map);
Permission getById(Integer id);
Integer create(Permission permission);
int update(Permission permission);
int delete(Integer id);
List<Permission> getList();
List<Permission> getByUserId(Integer userId);
}
\ No newline at end of file
package com.us.dao;
import com.us.bean.Role;
import java.util.List;
import java.util.Map;
public interface RoleDao {
List<Role> getByMap(Map<String, Object> map);
Role getById(Integer id);
Integer create(Role role);
int update(Role role);
int delete(Integer id);
}
\ No newline at end of file
package com.us.dao;
import com.us.bean.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List<User> getByMap(Map<String, Object> map);
User getById(Integer id);
Integer create(User user);
int update(User user);
int delete(Integer id);
User getByUserName(String userName);
}
\ No newline at end of file
package com.us.service;
import com.us.bean.Event;
import com.us.dao.EventDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class EventService {
@Autowired
private EventDao eventDao;
public List<Event> getByMap(Map<String,Object> map) {
return eventDao.getByMap(map);
}
public Event getById(Integer id) {
return eventDao.getById(id);
}
public Event create(Event event) {
eventDao.create(event);
return event;
}
public Event update(Event event) {
eventDao.update(event);
return event;
}
public int delete(Integer id) {
return eventDao.delete(id);
}
}
\ No newline at end of file
package com.us.service;
import com.us.bean.Permission;
import com.us.dao.PermissionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class PermissionService {
@Autowired
private PermissionDao permissionDao;
public List<Permission> getByMap(Map<String,Object> map) {
return permissionDao.getByMap(map);
}
public Permission getById(Integer id) {
return permissionDao.getById(id);
}
public Permission create(Permission permission) {
permissionDao.create(permission);
return permission;
}
public Permission update(Permission permission) {
permissionDao.update(permission);
return permission;
}
public int delete(Integer id) {
return permissionDao.delete(id);
}
}
\ No newline at end of file
package com.us.service;
import com.us.bean.Role;
import com.us.dao.RoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class RoleService {
@Autowired
private RoleDao roleDao;
public List<Role> getByMap(Map<String,Object> map) {
return roleDao.getByMap(map);
}
public Role getById(Integer id) {
return roleDao.getById(id);
}
public Role create(Role role) {
roleDao.create(role);
return role;
}
public Role update(Role role) {
roleDao.update(role);
return role;
}
public int delete(Integer id) {
return roleDao.delete(id);
}
}
\ No newline at end of file
package com.us.service;
import com.us.bean.User;
import com.us.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class UserService {
@Autowired
private UserDao userDao;
public List<User> getByMap(Map<String,Object> map) {
return userDao.getByMap(map);
}
public User getById(Integer id) {
return userDao.getById(id);
}
public User create(User user) {
userDao.create(user);
return user;
}
public User update(User user) {
userDao.update(user);
return user;
}
public int delete(Integer id) {
return userDao.delete(id);
}
public User getByUserName(String userName) {
return userDao.getByUserName(userName);
}
}
\ No newline at end of file
package com.us.shiro2;
import com.us.dao.PermissionDao;
import com.us.dao.UserDao;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
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.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* shiro配置类
* Created by cdyoue on 2016/10/21.
*/
@Configuration
public class ShiroConfiguration {
/**
* LifecycleBeanPostProcessor,这是个DestructionAwareBeanPostProcessor的子类,
* 负责org.apache.shiro.util.Initializable类型bean的生命周期的,初始化和销毁。
* 主要是AuthorizingRealm类的子类,以及EhCacheManager类。
*/
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* HashedCredentialsMatcher,这个类是为了对密码进行编码的,
* 防止密码在数据库里明码保存,当然在登陆认证的时候,
* 这个类也负责对form里输入的密码进行编码。
*/
@Bean(name = "hashedCredentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("MD5");
credentialsMatcher.setHashIterations(2);
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
}
/**ShiroRealm,这是个自定义的认证类,继承自AuthorizingRealm,
* 负责用户的认证和权限的处理,可以参考JdbcRealm的实现。
*/
@Bean(name = "shiroRealm")
@DependsOn("lifecycleBeanPostProcessor")
public ShiroRealm shiroRealm() {
ShiroRealm realm = new ShiroRealm();
// realm.setCredentialsMatcher(hashedCredentialsMatcher());
return realm;
}
// /**
// * EhCacheManager,缓存管理,用户登陆成功后,把用户信息和权限信息缓存起来,
// * 然后每次用户请求时,放入用户的session中,如果不设置这个bean,每个请求都会查询一次数据库。
// */
// @Bean(name = "ehCacheManager")
// @DependsOn("lifecycleBeanPostProcessor")
// public EhCacheManager ehCacheManager() {
// return new EhCacheManager();
// }
/**
* SecurityManager,权限管理,这个类组合了登陆,登出,权限,session的处理,是个比较重要的类。
// */
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
// securityManager.setCacheManager(ehCacheManager());
return securityManager;
}
/**
* ShiroFilterFactoryBean,是个factorybean,为了生成ShiroFilter。
* 它主要保持了三项数据,securityManager,filters,filterChainDefinitionManager。
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login");
// filters.put("logout",null);
shiroFilterFactoryBean.setFilters(filters);
Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>();
filterChainDefinitionManager.put("/logout", "logout");
filterChainDefinitionManager.put("/user/**", "authc,roles[ROLE_USER]");
filterChainDefinitionManager.put("/events/**", "authc,roles[ROLE_ADMIN]");
filterChainDefinitionManager.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
shiroFilterFactoryBean.setSuccessUrl("/");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
return shiroFilterFactoryBean;
}
/**
* DefaultAdvisorAutoProxyCreator,Spring的一个bean,由Advisor决定对哪些类的方法进行AOP代理。
*/
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
/**
* AuthorizationAttributeSourceAdvisor,shiro里实现的Advisor类,
* 内部使用AopAllianceAnnotationsAuthorizingMethodInterceptor来拦截用以下注解的方法。
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor aASA = new AuthorizationAttributeSourceAdvisor();
aASA.setSecurityManager(securityManager());
return aASA;
}
}
package com.us.shiro2;
import com.us.bean.Permission;
import com.us.bean.Role;
import com.us.bean.User;
import com.us.dao.PermissionDao;
import com.us.dao.UserDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by cdyoue on 2016/10/21.
*/
public class ShiroRealm extends AuthorizingRealm {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserDao userService;
@Autowired
private PermissionDao permissionService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
logger.info("doGetAuthorizationInfo+"+principalCollection.toString());
User user = userService.getByUserName((String) principalCollection.getPrimaryPrincipal());
//把principals放session中 key=userId value=principals
SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//赋予角色
for(Role userRole:user.getRoles()){
info.addRole(userRole.getName());
}
//赋予权限
for(Permission permission:permissionService.getByUserId(user.getId())){
// if(StringUtils.isNotBlank(permission.getPermCode()))
info.addStringPermission(permission.getName());
}
//设置登录次数、时间
// userService.updateUserLogin(user);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
logger.info("doGetAuthenticationInfo +" + authenticationToken.toString());
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName=token.getUsername();
logger.info(userName+token.getPassword());
User user = userService.getByUserName(token.getUsername());
if (user != null) {
// byte[] salt = Encodes.decodeHex(user.getSalt());
// ShiroUser shiroUser=new ShiroUser(user.getId(), user.getLoginName(), user.getName());
//设置用户session
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("user", user);
return new SimpleAuthenticationInfo(userName,user.getPassword(),getName());
} else {
return null;
}
// return null;
}
}
#local
server.contextPath=/
server.port=8080
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/epp_manager?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=admin
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
logging.config=classpath:log4j.properties
#local
# Output pattern : date [thread] priority category - message
log4j.rootLogger=INFO, Console, R
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
#/opt/apps/epp-manager/var/logs/epp-manager.log
log4j.appender.R.File=logs/epp-manager.log
log4j.appender.R.MaxFileSize=20MB
log4j.appender.R.MaxBackupIndex=30
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#Project defalult level
log4j.logger.com.us=INFO
#spring default level
log4j.logger.org.springframework=INFO
log4j.logger.org.springframework.jdbc=INFO
#apache
log4j.logger.org.apache=INFO
log4j.logger.org.activiti=INFO
log4j.logger.org.activiti.engine.impl.persistence.entity=INFO
log4j.logger.org.activiti.spring.SpringTransactionInterceptor=ERROR
#mybatis, debug level to see sql
log4j.logger.com.us.cmbms.dao=INFO
log4j.logger.com.us.workflow.dao=INFO
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.dao.EventDao">
<resultMap id="eventMap" type="com.us.bean.Event">
<id property="id" column="id"/>
<result property="rawEventId" column="raw_event_id"/>
<result property="host" column="host"/>
<result property="ip" column="ip"/>
<result property="source" column="source"/>
<result property="type" column="type"/>
<result property="startTime" column="start_time"/>
<result property="endTime" column="end_time"/>
<result property="content" column="content"/>
<result property="dataType" column="data_type"/>
<result property="suggest" column="suggest"/>
<result property="businessSystemId" column="business_system_id"/>
<result property="departmentId" column="department_id"/>
<result property="status" column="status"/>
<result property="occurCount" column="occur_count"/>
<result property="owner" column="owner"/>
<result property="responsedTime" column="responsed_time"/>
<result property="responsedBy" column="responsed_by"/>
<result property="resolvedTime" column="resolved_time"/>
<result property="resolvedBy" column="resolved_by"/>
<result property="closedTime" column="closed_time"/>
<result property="closedBy" column="closed_by"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="rawEventId != null and rawEventId != ''">
and raw_event_id = #{rawEventId}
</if>
<if test="host != null and host != ''">
and host = #{host}
</if>
<if test="ip != null and ip != ''">
and ip = #{ip}
</if>
<if test="source != null and source != ''">
and source = #{source}
</if>
<if test="type != null and type != ''">
and type = #{type}
</if>
<if test="startTime != null and startTime != ''">
and start_time = #{startTime}
</if>
<if test="endTime != null and endTime != ''">
and end_time = #{endTime}
</if>
<if test="content != null and content != ''">
and content = #{content}
</if>
<if test="dataType != null and dataType != ''">
and data_type = #{dataType}
</if>
<if test="suggest != null and suggest != ''">
and suggest = #{suggest}
</if>
<if test="businessSystemId != null and businessSystemId != ''">
and business_system_id = #{businessSystemId}
</if>
<if test="departmentId != null and departmentId != ''">
and department_id = #{departmentId}
</if>
<if test="status != null and status != ''">
and status = #{status}
</if>
<if test="occurCount != null and occurCount != ''">
and occur_count = #{occurCount}
</if>
<if test="owner != null and owner != ''">
and owner = #{owner}
</if>
<if test="responsedTime != null and responsedTime != ''">
and responsed_time = #{responsedTime}
</if>
<if test="responsedBy != null and responsedBy != ''">
and responsed_by = #{responsedBy}
</if>
<if test="resolvedTime != null and resolvedTime != ''">
and resolved_time = #{resolvedTime}
</if>
<if test="resolvedBy != null and resolvedBy != ''">
and resolved_by = #{resolvedBy}
</if>
<if test="closedTime != null and closedTime != ''">
and closed_time = #{closedTime}
</if>
<if test="closedBy != null and closedBy != ''">
and closed_by = #{closedBy}
</if>
<if test="keywords != null and keywords != ''">
and (
host like CONCAT('%', #{keywords},'%')
OR ip like CONCAT('%', #{keywords},'%')
OR source like CONCAT('%', #{keywords},'%')
OR type like CONCAT('%', #{keywords},'%')
OR content like CONCAT('%', #{keywords},'%')
OR suggest like CONCAT('%', #{keywords},'%')
OR status like CONCAT('%', #{keywords},'%')
OR owner like CONCAT('%', #{keywords},'%')
OR responsed_by like CONCAT('%', #{keywords},'%')
OR resolved_by like CONCAT('%', #{keywords},'%')
OR closed_by like CONCAT('%', #{keywords},'%')
)
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="eventMap">
SELECT * FROM event
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="eventMap">
SELECT * FROM event WHERE id =#{id}
</select>
<insert id="create" parameterType="com.us.bean.Event">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO event(
id,
raw_event_id,
host,
ip,
source,
type,
start_time,
end_time,
content,
data_type,
suggest,
business_system_id,
department_id,
status,
occur_count,
owner,
responsed_time,
responsed_by,
resolved_time,
resolved_by,
closed_time,
closed_by
)VALUES(
#{id},
#{rawEventId},
#{host},
#{ip},
#{source},
#{type},
#{startTime},
#{endTime},
#{content},
#{dataType},
#{suggest},
#{businessSystemId},
#{departmentId},
#{status},
#{occurCount},
#{owner},
#{responsedTime},
#{responsedBy},
#{resolvedTime},
#{resolvedBy},
#{closedTime},
#{closedBy}
)
</insert>
<update id="update" parameterType="com.us.bean.Event">
UPDATE event SET
raw_event_id = #{rawEventId},
host = #{host},
ip = #{ip},
source = #{source},
type = #{type},
start_time = #{startTime},
end_time = #{endTime},
content = #{content},
data_type = #{dataType},
suggest = #{suggest},
business_system_id = #{businessSystemId},
department_id = #{departmentId},
status = #{status},
occur_count = #{occurCount},
owner = #{owner},
responsed_time = #{responsedTime},
responsed_by = #{responsedBy},
resolved_time = #{resolvedTime},
resolved_by = #{resolvedBy},
closed_time = #{closedTime},
closed_by = #{closedBy}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM event WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.dao.PermissionDao">
<resultMap id="permissionMap" type="com.us.bean.Permission">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="permissionUrl" column="permission_url"/>
<result property="method" column="method"/>
<result property="description" column="description"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="permissionUrl != null and permissionUrl != ''">
and permission_url = #{permissionUrl}
</if>
<if test="method != null and method != ''">
and method = #{method}
</if>
<if test="description != null and description != ''">
and description = #{description}
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="permissionMap">
SELECT * FROM permission
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="permissionMap">
SELECT * FROM permission WHERE id =#{id}
</select>
<select id="getList" resultMap="permissionMap">
SELECT * from permission
</select>
<select id="getByUserId" parameterType="int" resultMap="permissionMap">
select p.*
from user u
LEFT JOIN user_role ur on u.id= ur.User_id
LEFT JOIN role r on ur.role_id=r.id
LEFT JOIN role_permission rp on rp.role_id=r.id
LEFT JOIN permission p on p.id =rp.permission_id
where u.id=#{userId}
</select>
<insert id="create" parameterType="com.us.bean.Permission">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO permission(
id,
name,
permission_url,
method,
description
)VALUES(
#{id},
#{name},
#{permissionUrl},
#{method},
#{description}
)
</insert>
<update id="update" parameterType="com.us.bean.Permission">
UPDATE permission SET
name = #{name},
permission_url = #{permissionUrl},
method = #{method},
description = #{description}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM permission WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.dao.RoleDao">
<resultMap id="roleMap" type="com.us.bean.Role">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="roleLevel" column="role_level"/>
<result property="description" column="description"/>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="roleLevel != null and roleLevel != ''">
and role_level = #{roleLevel}
</if>
<if test="description != null and description != ''">
and description = #{description}
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="roleMap">
SELECT * FROM role
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="roleMap">
SELECT * FROM role WHERE id =#{id}
</select>
<insert id="create" parameterType="com.us.bean.Role">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO role(
id,
name,
role_level,
description
)VALUES(
#{id},
#{name},
#{roleLevel},
#{description}
)
</insert>
<update id="update" parameterType="com.us.bean.Role">
UPDATE role SET
name = #{name},
role_level = #{roleLevel},
description = #{description}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM role WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.us.dao.UserDao">
<resultMap id="userMap" type="com.us.bean.User">
<id property="id" column="id"/>
<result property="cnname" column="cnname"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="telephone" column="telephone"/>
<result property="mobilePhone" column="mobile_phone"/>
<result property="wechatId" column="wechat_id"/>
<result property="skill" column="skill"/>
<result property="departmentId" column="department_id"/>
<result property="loginCount" column="login_count"/>
<collection property="roles" ofType="com.us.bean.Role">
<result column="name" property="name"/>
</collection>
</resultMap>
<sql id="queryCondition">
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="cnname != null and cnname != ''">
and cnname = #{cnname}
</if>
<if test="username != null and username != ''">
and username = #{username}
</if>
<if test="password != null and password != ''">
and password = #{password}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
<if test="telephone != null and telephone != ''">
and telephone = #{telephone}
</if>
<if test="mobilePhone != null and mobilePhone != ''">
and mobile_phone = #{mobilePhone}
</if>
<if test="wechatId != null and wechatId != ''">
and wechat_id = #{wechatId}
</if>
<if test="skill != null and skill != ''">
and skill = #{skill}
</if>
<if test="departmentId != null and departmentId != ''">
and department_id = #{departmentId}
</if>
<if test="loginCount != null and loginCount != ''">
and login_count = #{loginCount}
</if>
<if test="keywords != null and keywords != ''">
and (
cnname like CONCAT('%', #{keywords},'%')
OR username like CONCAT('%', #{keywords},'%')
OR telephone like CONCAT('%', #{keywords},'%')
OR mobile_phone like CONCAT('%', #{keywords},'%')
OR email like CONCAT('%', #{keywords},'%')
OR skill like CONCAT('%', #{keywords},'%')
OR wechat_id like CONCAT('%', #{keywords},'%')
)
</if>
</where>
</sql>
<select id="getByMap" parameterType="map" resultMap="userMap">
SELECT * FROM user
<include refid="queryCondition" />
</select>
<select id="getById" parameterType="int" resultMap="userMap">
SELECT * FROM user WHERE id =#{id}
</select>
<select id="getByUserName" parameterType="String" resultMap="userMap">
select u.*
,r.name
from user u
LEFT JOIN user_role ur on u.id= ur.user_id
LEFT JOIN role r on ur.role_id=r.id
where username= #{username}
</select>
<insert id="create" parameterType="com.us.bean.User">
<selectKey resultType="int" order="AFTER" keyProperty="id" >
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO user(
id,
cnname,
username,
password,
email,
telephone,
mobile_phone,
wechat_id,
skill,
department_id,
login_count
)VALUES(
#{id},
#{cnname},
#{username},
#{password},
#{email},
#{telephone},
#{mobilePhone},
#{wechatId},
#{skill},
#{departmentId},
#{loginCount}
)
</insert>
<update id="update" parameterType="com.us.bean.User">
UPDATE user SET
cnname = #{cnname},
username = #{username},
password = #{password},
email = #{email},
telephone = #{telephone},
mobile_phone = #{mobilePhone},
wechat_id = #{wechatId},
skill = #{skill},
department_id = #{departmentId},
login_count = #{loginCount}
WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment