下面列出了com.google.inject.servlet.RequestScoped#org.apache.shiro.SecurityUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 新增环境集群配置
*
* @param clusterEntity
* @param bindingResult
* @return
* @throws Exception
*/
@RequestMapping(value = "/", method = RequestMethod.POST)
public Response insert(@RequestBody @Valid ClusterEntity clusterEntity, BindingResult bindingResult) throws Exception {
Response response = new Response().success();
try {
if (ControllerUtil.checkResponse(response, bindingResult).failed()) {
return response;
}
if (StringUtils.isBlank(clusterEntity.getCluster())) {
clusterEntity.setCluster(ChronusConstants.DEF_CLUSTER);
}
String userName = (String) SecurityUtils.getSubject().getPrincipal();
clusterEntity.setCreatedBy(userName);
clusterEntity.setUpdatedBy(userName);
clusterService.insert(clusterEntity);
} catch (Exception e) {
log.error("新增环境配置异常! envEntity:{}", clusterEntity, e);
response.hinderFail("新增环境配置异常" + e.getMessage());
}
return response;
}
/**
* 添加提示的控制器
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/admin/addhint",method={RequestMethod.GET})
public ModelAndView AddHint() throws Exception {
ModelAndView mv = new ModelAndView("admin/addhint");
Subject currentUser = SecurityUtils.getSubject();
CommonUtils.setControllerName(request, mv);
CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv);
if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
currentUser.logout();
return new ModelAndView("redirect:/showinfo?err=-99");
}
List<Challenges> challs = challengeServices.getAllChallenges();
mv.addObject("allchalls", challs);
mv.setViewName("admin/addhint");
return mv;
}
/**
* 添加新闻的控制器
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/admin/addnews",method={RequestMethod.GET})
public ModelAndView AddNews() throws Exception {
ModelAndView mv = new ModelAndView("admin/addnews");
Subject currentUser = SecurityUtils.getSubject();
CommonUtils.setControllerName(request, mv);
CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv);
if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
currentUser.logout();
return new ModelAndView("redirect:/showinfo?err=-99");
}
mv.setViewName("admin/addnews");
return mv;
}
public ServiceITSetupImpl() {
super();
managementService = springResource.getBean( ManagementService.class );
applicationCreator = springResource.getBean( ApplicationCreator.class );
tokenService = springResource.getBean( TokenService.class );
providerFactory = springResource.getBean( SignInProviderFactory.class );
properties = springResource.getBean( "properties", Properties.class );
smf = springResource.getBean( ServiceManagerFactory.class );
exportService = springResource.getBean( ExportService.class );
importService = springResource.getBean( ImportService.class );
jobSchedulerService = springResource.getBean(JobSchedulerService.class);
try {
appInfoMigrationPlugin = springResource.getBean(GuiceFactory.class)
.getObject().getInstance(AppInfoMigrationPlugin.class);
} catch ( Exception e ) {
logger.error("Unable to instantiate AppInfoMigrationPlugin", e);
}
//set our security manager for shiro
SecurityUtils.setSecurityManager(springResource.getBean( org.apache.shiro.mgt.SecurityManager.class ));
}
public static MyShiroRealm.ShiroUser ShiroUser() {
MyShiroRealm.ShiroUser user= (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
return user;
/**
* 这个方式解决了拦截时候,从SecurityUtils.getSubject().getPrincipal()获取的对象为null,而强行转换而报错,但是返回的数据导致拦截器return false,而不能继续执行
* 目前验证码显示不出来,从而问题依旧没有解决
*/
// Object obj = SecurityUtils.getSubject().getPrincipal();
// MyShiroRealm.ShiroUser user = new MyShiroRealm.ShiroUser();
// if(obj==null){
// return new MyShiroRealm.ShiroUser();
// }
//
// if(obj instanceof MyShiroRealm.ShiroUser) {
// user = (MyShiroRealm.ShiroUser) obj;
// } else {
// System.out.print(obj.getClass()+"1111");
// user = JsonUtil.json2Bean(JsonUtil.bean2Json(obj), MyShiroRealm.ShiroUser.class);
// }
// return user;
}
@RequestMapping(value = "/register",method = RequestMethod.GET)
public ModelAndView doGetRegister() throws Exception {
ModelAndView mv = new ModelAndView("register");
Subject currentUser = SecurityUtils.getSubject();
CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv);
CommonUtils.setControllerName(request, mv);
if (currentUser.isAuthenticated()||currentUser.isRemembered())
{
return new ModelAndView("redirect:/home");
}
List<Countries> cts = countryServices.SelectAllCountry();
mv.addObject("country",cts);
mv.setViewName("register");
return mv;
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
boolean existSession = SecurityUtils.getSubject().isAuthenticated();
if (!existSession) {
return false;
} else {
Session session = SecurityUtils.getSubject().getSession(false);
if (session != null) {
Serializable id = session.getId();
if (id != null) {
if (redisClient.get((String) id) != null) {
return true;
}
}
}
return false;
}
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(SysUserAgent sysUserAgent,HttpServletRequest request) {
// Step.1 组装查询条件
QueryWrapper<SysUserAgent> queryWrapper = QueryGenerator.initQueryWrapper(sysUserAgent, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<SysUserAgent> pageList = sysUserAgentService.list(queryWrapper);
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "用户代理人设置列表");
mv.addObject(NormalExcelConstants.CLASS, SysUserAgent.class);
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户代理人设置列表数据", "导出人:"+user.getRealname(), "导出信息"));
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
@Test
public void testPrincipalWithType() {
Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
setSubject(subjectUnderTest);
Context context = new Context();
String result;
// Guest user
result = templateEngine.process(TEST_TEMPLATE_PATH, context);
assertFalse(result.contains("shiro:"));
assertFalse(result.contains("TYPEPRINCIPAL1"));
assertFalse(result.contains("TYPEPRINCIPAL2"));
// Logged in user
subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity
result = templateEngine.process(TEST_TEMPLATE_PATH, context);
assertFalse(result.contains("shiro:"));
assertTrue(result.contains("TYPEPRINCIPAL1<span>0</span>TYPEPRINCIPAL1"));
assertTrue(result.contains("TYPEPRINCIPAL20TYPEPRINCIPAL2"));
subjectUnderTest.logout();
}
/**
* 导出excel
*
* @param request
* @param response
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
// Step.1 组装查询条件
QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<SysDepart> pageList = sysDepartService.list(queryWrapper);
//按字典排序
Collections.sort(pageList, new Comparator<SysDepart>() {
@Override
public int compare(SysDepart arg0, SysDepart arg1) {
return arg0.getOrgCode().compareTo(arg1.getOrgCode());
}
});
//导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息"));
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}
public static void main(String[] args) {
//此处从ini文件来实现用用户角色权限配置,实际多从数据库表来实现
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini.bak");
//SercurityManager 对象
SecurityManager instance = factory.getInstance();
SecurityUtils.setSecurityManager(instance);
//测试用户
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");
boolean result = false;
try {
currentUser.login(token);
result = true;
LOG.debug("认证成功");
} catch (Exception e) {
result = false;
LOG.debug("认证失败");
}
}
@Override
protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
UsergridAuthorizationInfo info = (UsergridAuthorizationInfo)super.getAuthorizationInfo(principals);
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
session.setAttribute( "applications", info.getApplicationSet());
session.setAttribute("organizations", info.getOrganizationSet());
if ( info.getOrganization() != null ) {
session.setAttribute( "organization", info.getOrganization() );
}
if ( info.getApplication() != null ) {
session.setAttribute( "application", info.getApplication() );
}
return info;
}
public static Session getSession(){
try{
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession(false);
if (session == null){
session = subject.getSession();
}
if (session != null){
return session;
}
// subject.logout();
}catch (InvalidSessionException e){
}
return null;
}
@Test
public void testAuthorization1() throws Exception {
try {
SecurityUtils.setSecurityManager(new DefaultSecurityManager());
new ShiroJwtProvider(Mockito.mock(AppContext.class));
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
Mockito.when(req.getHeader("Authorization")).thenReturn("Bearer ");
ShiroJwtVerifyingFilter filter = new ShiroJwtVerifyingFilter();
Assertions.assertThat(
filter.isAccessAllowed(
req,
Mockito.mock(ServletResponse.class),
Mockito.mock(Object.class)))
.isFalse();
} finally {
ThreadContext.unbindSubject();
ThreadContext.unbindSecurityManager();
}
}
/**
* 登录
*
* @param username
* @param password
* @return
*/
@PostMapping("/login")
@ResponseBody
public Object submitLogin(String username, String password, boolean rememberMe, String kaptcha) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
try {
// 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
// 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
// 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
currentUser.login(token);
System.out.println("登录成功!");
return 200;
} catch (Exception e) {
logger.error("登录失败,用户名[{}]", username, e);
token.clear();
return 500;
}
}
/**
* 添加提示的控制器
*
* @return
* @throws Exception
*/
@RequestMapping(value = "/admin/addhint",method={RequestMethod.GET})
public ModelAndView AddHint() throws Exception {
ModelAndView mv = new ModelAndView("admin/addhint");
Subject currentUser = SecurityUtils.getSubject();
CommonUtils.setControllerName(request, mv);
CommonUtils.setUserInfo(currentUser, userServices, submissionServices,mv);
if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
currentUser.logout();
return new ModelAndView("redirect:/showinfo?err=-99");
}
List<Challenges> challs = challengeServices.getAllChallenges();
mv.addObject("allchalls", challs);
mv.setViewName("admin/addhint");
return mv;
}
/**
* 文件上传主页入口方法
*
* @param model {@link Model}
* @return JSP页面
*/
@RequestMapping("fileupload")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
if (user.getPercode().equals(ADMIN)) {
return ADMIN;
}
boolean firstLogin = userService.isFirstLogin(user.getUid());
if (firstLogin) {
return "jsp/firstpd.jsp";
}
//用户上传历史实体
List<History> userHistoryList = fileService.getUserHistoryByUserId(user.getUid());
//Student浏览区数据
// orderInfoList already filtered with state
model.addAttribute("orderInfoStudentFullList", fileService.getOrderInfoFullEntity());
//下拉框数据
model.addAttribute("orderInfoList", fileService.getOrderInfoEntity());
model.addAttribute("user", user);
model.addAttribute("userHistoryList", userHistoryList);
return "jsp/fileupload.jsp";
}
public SysUserVO getCurrentUser(){
Tools.executeLogin();
Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()){
throw new RequestException(ResponseCode.NOT_SING_IN);
}
JwtToken jwtToken = new JwtToken();
Object principal = subject.getPrincipal();
if(principal==null){
throw RequestException.fail("用户信息获取失败");
}
BeanUtils.copyProperties(principal,jwtToken);
SysUser user = this.findUserByName(jwtToken.getUsername(),false);
if(user==null){
throw RequestException.fail("用户不存在");
}
//获取菜单/权限信息
List<SysResource> allPer = userRolesRegexResource(roleService.findAllRoleByUserId(user.getId(),true));
SysUserVO vo = new SysUserVO();
BeanUtils.copyProperties(user,vo);
vo.setResources(allPer);
return vo;
}
/**
* 验证用户是否具有以下任意一个角色。
* @param roleNames 以 delimeter 为分隔符的角色列表
* @param delimeter 角色列表分隔符
* @return 用户是否具有以下任意一个角色
*/
public boolean hasAnyRoles(String roleNames, String delimeter) {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
if (delimeter == null || delimeter.length() == 0) {
delimeter = ROLE_NAMES_DELIMETER;
}
for (String role : roleNames.split(delimeter)) {
if (subject.hasRole(role.trim()) == true) {
return true;
}
}
}
return false;
}
/**
* 登录
*/
@ResponseBody
@PostMapping("/login")
public JsonResult doLogin(String username, String password, String code, HttpServletRequest request) {
if (StringUtil.isBlank(username, password)) {
return JsonResult.error("账号密码不能为空");
}
if (!CaptchaUtil.ver(code, request)) {
CaptchaUtil.clear(request);
return JsonResult.error("验证码不正确");
}
try {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
SecurityUtils.getSubject().login(token);
addLoginRecord(getLoginUserId(), request);
return JsonResult.ok("登录成功");
} catch (IncorrectCredentialsException ice) {
return JsonResult.error("密码错误");
} catch (UnknownAccountException uae) {
return JsonResult.error("账号不存在");
} catch (LockedAccountException e) {
return JsonResult.error("账号被锁定");
} catch (ExcessiveAttemptsException eae) {
return JsonResult.error("操作频繁,请稍后再试");
}
}
@RequestMapping(value="admin/mails",method = {RequestMethod.GET})
public ModelAndView Mails() throws Exception {
ModelAndView mv = new ModelAndView("admin/mails");
Subject currentUser = SecurityUtils.getSubject();
CommonUtils.setControllerName(request, mv);
CommonUtils.setUserInfo(currentUser, userServices, teamServices,submissionServices,mv);
if (CommonUtils.CheckIpBanned(request, bannedIpServices)) {
currentUser.logout();
return new ModelAndView("redirect:/showinfo?err=-99");
}
String uid = request.getParameter("target");
Users touser= null;
if (uid!=null && uid.length()>0 && StringUtils.isNumeric(uid) && (touser = userServices.getUserById(Long.valueOf(uid)))!=null) {
mv.addObject("target", touser.getEmail());
} else if (uid!=null) {
return new ModelAndView("redirect:/showinfo?err=404");
}
mv.setViewName("admin/mails");
return mv;
}
/**
* 应用日志存储
* */
@After("operLogCut() && @annotation(operLog)")
public void logAdvisor(BizOperLog operLog){
log.info("进入操作日志切面");
// 添加记录日志
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
UserTest user = (UserTest)SecurityUtils.getSubject().getPrincipal();
String userid = user.getId();// 操作员ID
String loginName = user.getLoginName();
String ipAddr = IPUtil.getIpAddr(request);// 访问段ip
//从注解中获取操作类型和备注
String opertype = operLog.operType().getValue();
String memo = operLog.memo();
sysOperLogServiceImpl.insertOperLog(userid,loginName,ipAddr,opertype,memo);
log.info("记录操作日志成功");
}
@PostMapping("login")
@ResponseBody
public MyResponse login(@NotBlank String username, @NotBlank String password, boolean rememberMe) {
try {
//shiro通过SecurityUtils.getSubject()获得主体,主体可以理解为客户端实例,原理在后面讲
Subject subject = SecurityUtils.getSubject();
//已经认证过,也就是该客户端已经登陆过
if (subject.isAuthenticated()) {
return MyResponse.createResponse(ResponseEnum.ALREADY_LOGIN);
}
//一般都使用UsernamePasswordToken,shiro的token中有Principal和Credentials的概念
//Principal代表当前客户端要登录的用户,Credentials代表证明该用户身份的凭证
//UsernamePasswordToken将username作为Principal,password作为Credentials
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//rememberMe功能后面讲
token.setRememberMe(rememberMe);
subject.login(token);
return MyResponse.createResponse(ResponseEnum.SUCC);
} catch (AuthenticationException e) {
// 用户名或密码错误,不应该明确返回到底是用户不存在还是密码错误
return MyResponse.createResponse(ResponseEnum.ILLEGAL_PARAM);
}
}
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
try {
Serializable id = SecurityUtils.getSubject().getSession(false).getId();
byte[] value = redisClient.get((String) id);
if (value != null) {
UserInfo userInfo = SerializeUtil.deserialize(value, UserInfo.class);
redisClient.expire((String) id, userInfo.getExpireTime() == null ? SsoConstants.DEFAULT_LOGIN_EXPIRE : userInfo.getExpireTime());
}
} catch (Exception e) {
logger.error("error ", e);
}
return true;
}
/**
* 用户组分配角色
* @param groupId 用户组id
* @param roleIds 角色id集合
* @return
*/
@ResponseBody
@RequiresPermissions("system:group:allowRole")
@MumuLog(name = "用户群组分配角色",operater = "POST")
@RequestMapping(value = {"/allowRole"}, method = RequestMethod.POST)
public ResponseEntity saveGroupRole(String groupId, String roleIds) {
String loginName = SecurityUtils.getSubject().getPrincipal().toString();
try {
groupRoleService.saveGroupRole(groupId, roleIds, loginName);
} catch (Exception e) {
log.error(e);
return new ResponseEntity(500, "用户组角色保存出现异常", null);
}
return new ResponseEntity(200, "用户组角色保存成功", null);
}
/**
* 文件上传方法
*
* @param file {@link MultipartFile}
* @return index.jsp
* @throws Exception Exception
*/
@RequestMapping("fileup")
public String upfileByID(MultipartFile[] file) throws Exception {
if (file == null) {
throw new FileException("上传失败:未获取到上传内容!");
}
User user = (User) SecurityUtils.getSubject().getPrincipal();
for (MultipartFile file1 : file) {
if (user.getUserSelectOid() != null && !(file1.isEmpty())) {
fileService.uploadFile(file1, user);
}
}
return "index.jsp";
}
@RequestMapping("/login")
public String login() {
Subject subject = SecurityUtils.getSubject();
if (subject.isAuthenticated()) {
return "redirect:/index";
}
return "front/login";
}
/**
* Post Login
* Returns userName & password
* for anonymous access, username is always anonymous.
* After getting this ticket, access through websockets become safe
*
* @return 200 response
*/
@POST
@ZeppelinApi
public Response postLogin(@FormParam("userName") String userName,
@FormParam("password") String password) {
LOG.debug("userName: {}", userName);
// ticket set to anonymous for anonymous user. Simplify testing.
Subject currentUser = SecurityUtils.getSubject();
if (currentUser.isAuthenticated()) {
currentUser.logout();
}
LOG.debug("currentUser: {}", currentUser);
JsonResponse<Map<String, String>> response = null;
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
response = proceedToLogin(currentUser, token);
}
if (response == null) {
response = new JsonResponse<>(Response.Status.FORBIDDEN, "", null);
}
LOG.info(response.toString());
return response.build();
}
/**
* 获取平台登录用户
* @return
*/
public static User getLoginUser() {
User user = new User();
if (ShiroUtils.isAuthenticated()) {
user = (User) SecurityUtils.getSubject().getSession().getAttribute(Consts.SESSION_USER);
}
return user;
}
/**
* 导出excel
*
* @param request
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(SysDict sysDict,HttpServletRequest request) {
// Step.1 组装查询条件
QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, request.getParameterMap());
//Step.2 AutoPoi 导出Excel
ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
List<SysDictPage> pageList = new ArrayList<SysDictPage>();
List<SysDict> sysDictList = sysDictService.list(queryWrapper);
for (SysDict dictMain : sysDictList) {
SysDictPage vo = new SysDictPage();
BeanUtils.copyProperties(dictMain, vo);
// 查询机票
List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId(dictMain.getId());
vo.setSysDictItemList(sysDictItemList);
pageList.add(vo);
}
// 导出文件名称
mv.addObject(NormalExcelConstants.FILE_NAME, "数据字典");
// 注解对象Class
mv.addObject(NormalExcelConstants.CLASS, SysDictPage.class);
// 自定义表格参数
LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据字典列表", "导出人:"+user.getRealname(), "数据字典"));
// 导出数据列表
mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
return mv;
}