增加博客权限认证
This commit is contained in:
parent
99c08f6eca
commit
006149e5f3
|
@ -0,0 +1,26 @@
|
|||
package com.len.util;
|
||||
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
|
||||
/**
|
||||
* @author zhuxiaomeng
|
||||
* @date 2018/8/18.
|
||||
* @email 154040976@qq.com
|
||||
*/
|
||||
public class CustomUsernamePasswordToken extends UsernamePasswordToken {
|
||||
|
||||
private String type;
|
||||
|
||||
public CustomUsernamePasswordToken(final String username, final String password, String loginType) {
|
||||
super(username,password);
|
||||
this.type = loginType;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
|
@ -7,6 +7,7 @@ import com.len.entity.SysMenu;
|
|||
import com.len.entity.SysUser;
|
||||
import com.len.service.MenuService;
|
||||
import com.len.service.SysUserService;
|
||||
import com.len.util.CustomUsernamePasswordToken;
|
||||
import com.len.util.VerifyCodeUtils;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
@ -14,7 +15,6 @@ import org.apache.shiro.SecurityUtils;
|
|||
import org.apache.shiro.authc.ExcessiveAttemptsException;
|
||||
import org.apache.shiro.authc.IncorrectCredentialsException;
|
||||
import org.apache.shiro.authc.UnknownAccountException;
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
import org.apache.shiro.session.Session;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
@ -84,24 +84,49 @@ public class LoginController {
|
|||
@ApiOperation(value = "/login", httpMethod = "POST", notes = "登录method")
|
||||
@PostMapping(value = "/login")
|
||||
public String login(SysUser user, Model model, String rememberMe, HttpServletRequest request) {
|
||||
String codeMsg = (String) request.getAttribute("shiroLoginFailure");
|
||||
/*String codeMsg = (String) request.getAttribute("shiroLoginFailure");
|
||||
if ("code.error".equals(codeMsg)) {
|
||||
model.addAttribute("message", "验证码错误");
|
||||
return "/login";
|
||||
}
|
||||
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername().trim(),
|
||||
user.getPassword());
|
||||
}*/
|
||||
CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(user.getUsername().trim(),
|
||||
user.getPassword(), "UserLogin");
|
||||
Subject subject = ShiroUtil.getSubject();
|
||||
String msg = null;
|
||||
try {
|
||||
subject.login(token);
|
||||
//subject.hasRole("admin");
|
||||
if (subject.isAuthenticated()) {
|
||||
return "redirect:/main";
|
||||
}
|
||||
} catch (UnknownAccountException e) {
|
||||
} catch (UnknownAccountException | IncorrectCredentialsException e) {
|
||||
msg = "用户名/密码错误";
|
||||
} catch (IncorrectCredentialsException e) {
|
||||
} catch (ExcessiveAttemptsException e) {
|
||||
msg = "登录失败多次,账户锁定10分钟";
|
||||
}
|
||||
if (msg != null) {
|
||||
model.addAttribute("message", msg);
|
||||
}
|
||||
return "/login";
|
||||
}
|
||||
|
||||
@ApiOperation(value = "/blogLogin", httpMethod = "POST", notes = "登录method")
|
||||
@PostMapping(value = "/blogLogin")
|
||||
public String blogLogin(SysUser user, Model model, String rememberMe, HttpServletRequest request) {
|
||||
/*String codeMsg = (String) request.getAttribute("shiroLoginFailure");
|
||||
if ("code.error".equals(codeMsg)) {
|
||||
model.addAttribute("message", "验证码错误");
|
||||
return "/login";
|
||||
}*/
|
||||
CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(user.getUsername().trim(),
|
||||
user.getPassword(), "BlogLogin");
|
||||
Subject subject = ShiroUtil.getSubject();
|
||||
String msg = null;
|
||||
try {
|
||||
subject.login(token);
|
||||
if (subject.isAuthenticated()) {
|
||||
return "redirect:/main";
|
||||
}
|
||||
} catch (UnknownAccountException | IncorrectCredentialsException e) {
|
||||
msg = "用户名/密码错误";
|
||||
} catch (ExcessiveAttemptsException e) {
|
||||
msg = "登录失败多次,账户锁定10分钟";
|
||||
|
@ -113,7 +138,7 @@ public class LoginController {
|
|||
}
|
||||
|
||||
@GetMapping("/main")
|
||||
public String main(){
|
||||
public String main() {
|
||||
return "main/main";
|
||||
}
|
||||
|
||||
|
@ -162,7 +187,7 @@ public class LoginController {
|
|||
|
||||
//生成随机字串
|
||||
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
|
||||
log.info("verifyCode:{}",verifyCode);
|
||||
log.info("verifyCode:{}", verifyCode);
|
||||
//存入会话session
|
||||
HttpSession session = request.getSession(true);
|
||||
session.setAttribute("_code", verifyCode.toLowerCase());
|
||||
|
|
|
@ -0,0 +1,128 @@
|
|||
package com.len.core.shiro;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.len.base.CurrentMenu;
|
||||
import com.len.base.CurrentRole;
|
||||
import com.len.base.CurrentUser;
|
||||
import com.len.entity.SysMenu;
|
||||
import com.len.entity.SysRole;
|
||||
import com.len.entity.SysUser;
|
||||
import com.len.service.MenuService;
|
||||
import com.len.service.RoleMenuService;
|
||||
import com.len.service.RoleUserService;
|
||||
import com.len.service.SysUserService;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
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.realm.Realm;
|
||||
import org.apache.shiro.session.Session;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
import org.apache.shiro.util.ByteSource;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author zhuxiaomeng
|
||||
* @date 2017/12/4.
|
||||
* @email 154040976@qq.com
|
||||
*/
|
||||
@Service
|
||||
public class BlogRealm extends AuthorizingRealm {
|
||||
|
||||
@Autowired
|
||||
private SysUserService userService;
|
||||
|
||||
@Autowired
|
||||
private MenuService menuService;
|
||||
|
||||
@Autowired
|
||||
private RoleUserService roleUserService;
|
||||
|
||||
@Autowired
|
||||
private RoleMenuService roleMenuService;
|
||||
|
||||
/* @Override
|
||||
public boolean supports(AuthenticationToken token) {
|
||||
return super.supports(token);
|
||||
}*/
|
||||
|
||||
/**
|
||||
* 获取认证
|
||||
* @param principalCollection
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
|
||||
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
|
||||
String name= (String) principalCollection.getPrimaryPrincipal();
|
||||
//根据用户获取角色 根据角色获取所有按钮权限
|
||||
CurrentUser cUser= (CurrentUser) ShiroUtil.getSession().getAttribute("curentUser");
|
||||
for(CurrentRole cRole:cUser.getCurrentRoleList()){
|
||||
info.addRole(cRole.getId());
|
||||
}
|
||||
for(CurrentMenu cMenu:cUser.getCurrentMenuList()){
|
||||
if(!StringUtils.isEmpty(cMenu.getPermission()))
|
||||
info.addStringPermission(cMenu.getPermission());
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权
|
||||
* @param authenticationToken
|
||||
* @return
|
||||
* @throws AuthenticationException
|
||||
*/
|
||||
@Override
|
||||
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
|
||||
throws AuthenticationException {
|
||||
UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
|
||||
String name=upToken.getUsername();
|
||||
String username=(String)authenticationToken.getPrincipal();
|
||||
SysUser s=null;
|
||||
try {
|
||||
s = userService.login(username);
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
if(s==null){
|
||||
throw new UnknownAccountException("账户密码不正确");
|
||||
}else{
|
||||
CurrentUser currentUser=new CurrentUser(s.getId(),s.getUsername(),s.getAge(),s.getEmail(),s.getPhoto(),s.getRealName());
|
||||
Subject subject = ShiroUtil.getSubject();
|
||||
/**角色权限封装进去*/
|
||||
//根据用户获取菜单
|
||||
List<SysMenu> menuList=new ArrayList<>(new HashSet<>(menuService.getUserMenu(s.getId())));
|
||||
JSONArray json=menuService.getMenuJsonByUser(menuList);
|
||||
Session session= subject.getSession();
|
||||
session.setAttribute("menu",json);
|
||||
CurrentMenu currentMenu=null;
|
||||
List<CurrentMenu> currentMenuList=new ArrayList<>();
|
||||
List<SysRole> roleList=new ArrayList<>();
|
||||
for(SysMenu m:menuList){
|
||||
currentMenu=new CurrentMenu(m.getId(),m.getName(),m.getPId(),m.getUrl(),m.getOrderNum(),m.getIcon(),m.getPermission(),m.getMenuType(),m.getNum());
|
||||
currentMenuList.add(currentMenu);
|
||||
roleList.addAll(m.getRoleList());
|
||||
}
|
||||
roleList= new ArrayList<>(new HashSet<>(roleList));
|
||||
List<CurrentRole> currentRoleList=new ArrayList<>();
|
||||
CurrentRole role=null;
|
||||
for(SysRole r:roleList){
|
||||
role=new CurrentRole(r.getId(),r.getRoleName(),r.getRemark());
|
||||
currentRoleList.add(role);
|
||||
}
|
||||
currentUser.setCurrentRoleList(currentRoleList);
|
||||
currentUser.setCurrentMenuList(currentMenuList);
|
||||
session.setAttribute("curentUser",currentUser);
|
||||
}
|
||||
ByteSource byteSource=ByteSource.Util.bytes(username);
|
||||
return new SimpleAuthenticationInfo(username,s.getPassword(), byteSource, getName());
|
||||
}
|
||||
}
|
|
@ -25,6 +25,7 @@ import org.apache.shiro.authc.UsernamePasswordToken;
|
|||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.realm.AuthorizingRealm;
|
||||
import org.apache.shiro.realm.Realm;
|
||||
import org.apache.shiro.session.Session;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
|
@ -38,7 +39,7 @@ import org.springframework.stereotype.Service;
|
|||
* @email 154040976@qq.com
|
||||
*/
|
||||
@Service
|
||||
public class LoginRealm extends AuthorizingRealm{
|
||||
public class LoginRealm extends AuthorizingRealm {
|
||||
|
||||
@Autowired
|
||||
private SysUserService userService;
|
||||
|
|
|
@ -0,0 +1,37 @@
|
|||
package com.len.config;
|
||||
|
||||
import com.len.util.CustomUsernamePasswordToken;
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
import org.apache.shiro.authc.AuthenticationInfo;
|
||||
import org.apache.shiro.authc.AuthenticationToken;
|
||||
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
|
||||
import org.apache.shiro.realm.Realm;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @author zhuxiaomeng
|
||||
* @date 2018/8/18.
|
||||
* @email 154040976@qq.com
|
||||
* 多模块认证
|
||||
*/
|
||||
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {
|
||||
|
||||
@Override
|
||||
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
|
||||
assertRealmsConfigured();
|
||||
CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;
|
||||
String type = token.getType();
|
||||
Collection<Realm> realms = getRealms();
|
||||
Collection<Realm> realmsList = new ArrayList<>();
|
||||
for (Realm realm : realms) {
|
||||
if (realm.getName().contains(type)) {
|
||||
realmsList.add(realm);
|
||||
}
|
||||
}
|
||||
return realmsList.size() == 1 ? doSingleRealmAuthentication(realmsList.iterator().next(), token)
|
||||
: doMultiRealmAuthentication(realmsList, token);
|
||||
}
|
||||
}
|
|
@ -2,14 +2,13 @@ package com.len.config;
|
|||
|
||||
import com.len.core.filter.PermissionFilter;
|
||||
import com.len.core.filter.VerfityCodeFilter;
|
||||
import com.len.core.shiro.BlogRealm;
|
||||
import com.len.core.shiro.LoginRealm;
|
||||
import com.len.core.shiro.RetryLimitCredentialsMatcher;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.Filter;
|
||||
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
|
||||
import org.apache.shiro.cache.ehcache.EhCacheManager;
|
||||
import org.apache.shiro.mgt.SecurityManager;
|
||||
import org.apache.shiro.realm.Realm;
|
||||
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
|
||||
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
|
||||
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
|
||||
|
@ -17,10 +16,11 @@ import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
|
|||
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
|
||||
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.filter.DelegatingFilterProxy;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author zhuxiaomeng
|
||||
|
@ -41,12 +41,18 @@ public class ShiroConfig {
|
|||
return rm;
|
||||
|
||||
}
|
||||
@Bean(name = "loginRealm")
|
||||
@Bean(name = "userLoginRealm")
|
||||
public LoginRealm getLoginRealm(){
|
||||
LoginRealm realm= new LoginRealm();
|
||||
realm.setCredentialsMatcher(getRetryLimitCredentialsMatcher());
|
||||
return realm;
|
||||
}
|
||||
@Bean(name = "blogLoginRealm")
|
||||
public BlogRealm blogLoginRealm(){
|
||||
BlogRealm realm= new BlogRealm();
|
||||
realm.setCredentialsMatcher(getRetryLimitCredentialsMatcher());
|
||||
return realm;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EhCacheManager getCacheManager(){
|
||||
|
@ -60,10 +66,28 @@ public class ShiroConfig {
|
|||
return new LifecycleBeanPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AtLeastOneSuccessfulStrategy getAtLeastOneSuccessfulStrategy(){
|
||||
AtLeastOneSuccessfulStrategy strategy=new AtLeastOneSuccessfulStrategy();
|
||||
return strategy;
|
||||
}
|
||||
@Bean
|
||||
public MyModularRealmAuthenticator getMyModularRealmAuthenticator(){
|
||||
MyModularRealmAuthenticator authenticator=new MyModularRealmAuthenticator();
|
||||
authenticator.setAuthenticationStrategy(getAtLeastOneSuccessfulStrategy());
|
||||
return authenticator;
|
||||
}
|
||||
@Bean(name="securityManager")
|
||||
public SecurityManager getSecurityManager(@Qualifier("loginRealm") LoginRealm loginRealm){
|
||||
public SecurityManager getSecurityManager(@Qualifier("userLoginRealm") LoginRealm loginRealm,
|
||||
@Qualifier("blogLoginRealm") BlogRealm blogLoginRealm){
|
||||
DefaultWebSecurityManager dwm=new DefaultWebSecurityManager();
|
||||
dwm.setRealm(loginRealm);
|
||||
List<Realm> loginRealms=new ArrayList<>();
|
||||
dwm.setAuthenticator(getMyModularRealmAuthenticator());
|
||||
loginRealm.setName("UserLogin");
|
||||
blogLoginRealm.setName("BlogLogin");
|
||||
loginRealms.add(loginRealm);
|
||||
loginRealms.add(blogLoginRealm);
|
||||
dwm.setRealms(loginRealms);
|
||||
dwm.setCacheManager(getCacheManager());
|
||||
dwm.setSessionManager(defaultWebSessionManager());
|
||||
return dwm;
|
||||
|
@ -96,6 +120,7 @@ public class ShiroConfig {
|
|||
sfb.setFilters(filters);
|
||||
Map<String, String> filterMap = new LinkedHashMap<>();
|
||||
filterMap.put("/login","verCode,anon");
|
||||
filterMap.put("/blogLogin","verCode,anon");
|
||||
//filterMap.put("/login","anon");
|
||||
filterMap.put("/getCode","anon");
|
||||
filterMap.put("/blog/**","anon");
|
||||
|
|
Loading…
Reference in New Issue