本文整理匯總了Java中org.apache.shiro.SecurityUtils.getSubject方法的典型用法代碼示例。如果您正苦於以下問題:Java SecurityUtils.getSubject方法的具體用法?Java SecurityUtils.getSubject怎麽用?Java SecurityUtils.getSubject使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.shiro.SecurityUtils
的用法示例。
在下文中一共展示了SecurityUtils.getSubject方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: login
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@RequestMapping("/login")
@ResponseBody
public BaseResponse<User> login(UserToken user, HttpServletRequest request) {
BaseResponse<User> res = new BaseResponse<>();
try {
ShiroToken token = new ShiroToken(user.getUsername(), user.getPassword());
Subject currentUser = SecurityUtils.getSubject();
currentUser.login(token);
//request.getSession().setAttribute("user", login);
//res.setBody(login);
res.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
res.setSuccess(false);
res.setMessage(e.getMessage());
LOGGER.error(e.getMessage(), e);
}
return res;
}
示例2: index
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@ApiOperation(value = "後台首頁")
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(ModelMap modelMap) {
// 已注冊係統
UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
upmsSystemExample.createCriteria()
.andStatusEqualTo((byte) 1);
List<UpmsSystem> upmsSystems = upmsSystemService.selectByExample(upmsSystemExample);
modelMap.put("upmsSystems", upmsSystems);
// 當前登錄用戶權限
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
modelMap.put("upmsPermissions", upmsPermissions);
return "/manage/index.jsp";
}
示例3: login
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@RequestMapping(value = "/tlogin", method = RequestMethod.POST)
public String login(String username, String password, HttpServletRequest request) {
//String validateCode = (String) ServletActionContext.getRequest().getSession().getAttribute("key");
// if (StringUtils.isNotBlank(checkcode) && checkcode.equals(validateCode)) {
// 使用shiri方式
// 獲得當前對象的狀態:未認證
Subject subject = SecurityUtils.getSubject();
// 用戶名密碼令牌對象
AuthenticationToken token = new UsernamePasswordToken(username,
password);
try {
subject.login(token);
} catch (Exception e) {
e.printStackTrace();
return "login";
}
User user = (User) subject.getPrincipal();
// user放入session
request.getSession().setAttribute("loginUser", user);
return "index";
}
示例4: userGet
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@RequestMapping("/userGet")
@ResponseBody
public String userGet(HttpServletRequest req,HttpServletResponse respon)throws Exception{
Subject currentUser = SecurityUtils.getSubject();
LOGGER.info("userinfo------->{}",JSON.toJSONString(currentUser.getPrincipal()));
/* String userNameString = req.getRemoteUser();
System.out.println("username---->"+userNameString);
AttributePrincipal principal = (AttributePrincipal) req.getUserPrincipal();
if (null != principal) {
Map<String, Object> attMap = principal.getAttributes();
for (Entry<String, Object> entry : attMap.entrySet()) {
System.out.println("===> | " + entry.getKey() + "=:" + entry.getValue() + "<br>");
}
String username = null;
if (null != principal) {
username = principal.getName();
System.out.println("<span style='color:red;'>" + username + "</span><br>");
}
} */
return (String) currentUser.getPrincipal();
}
示例5: login
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
/**
* 登錄
* @param user
* @param session
* @param request
* @return
* @throws Exception
*/
@SystemControllerLog(description="登錄係統")
@RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView login(User user, HttpSession session,HttpServletRequest request) throws Exception{
ModelAndView mv = new ModelAndView();
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getUserPass());
try{
currentUser.login(token);
mv.setViewName("redirect:/index.jsp");
} catch (AuthenticationException e){
mv.addObject("message", "login errors");
mv.setViewName("redirect:/backend/login");
}
return mv;
}
示例6: tryLogin
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
public boolean tryLogin(String email, String password, Boolean rememberMe) {
org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(email, password);
token.setRememberMe(rememberMe);
try {
currentUser.login(token);
System.out.println("User [" + currentUser.getPrincipal().toString() + "] logged in successfully.");
// save username in the session
currentUser.getSession().setAttribute("username", email);
return true;
} catch (UnknownAccountException uae) {
System.out.println("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
System.out.println("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
System.out.println("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it.");
}
return false;
}
示例7: testIniAuthorization
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
/**
* testIniAuthorization
* @Description: 使用inirealm完成授權
* @return: void
* @Author: BeautifulSoup
* @Date: 2017年12月16日 下午3:05:34
*/
@Test
@Ignore
public void testIniAuthorization(){
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:permission-shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
//首先認證,認證通過之後才能授權
UsernamePasswordToken token=new UsernamePasswordToken("beautifulsoup", "password");
try{
subject.login(token);
}catch(AuthenticationException e){
e.printStackTrace();
}
System.out.println("用戶的認證狀態:"+subject.isAuthenticated());
boolean isPermitted=subject.isPermittedAll("user:create:01","user:query");
subject.checkPermissions("user:create:01","user:query");
System.out.println(isPermitted);
}
示例8: hasAnyPermissions
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
/**
* 驗證用戶是否具有以下任意一個權限。
* @param permissions 以 delimeter 為分隔符的權限列表
* @param delimeter 權限列表分隔符
* @return 用戶是否具有以下任意一個權限
*/
public boolean hasAnyPermissions(String permissions, String delimeter) {
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
if (delimeter == null || delimeter.length() == 0) {
delimeter = PERMISSION_NAMES_DELIMETER;
}
for (String permission : permissions.split(delimeter)) {
if (permission != null && subject.isPermitted(permission.trim()) == true) {
return true;
}
}
}
return false;
}
示例9: testCustomRealm
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
/**
* testCustomRealm
* @Description: CustomRealm的測試
* @return: void
* @Author: BeautifulSoup
* @Date: 2017年12月16日 上午11:41:53
*/
@Test
public void testCustomRealm(){
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:customrealm-shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken("BeautifulSoup", "1997admin");
try{
subject.login(token);
}catch(AuthenticationException e){
e.printStackTrace();
}
System.out.println("用戶認證狀態:"+subject.isAuthenticated());
subject.logout();
System.out.println("用戶當前認證狀態:"+subject.isAuthenticated());
}
示例10: logout
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@RequestMapping(value = "/user/logout",method = RequestMethod.GET)
@ApiOperation(value = "退出登錄")
public Result<Object> logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return new ResultUtil<Object>().setData(null);
}
示例11: auth
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
public static void auth(final String[] filters) {
final Filter f = (req, res) -> {
final Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
// 未授權
halt(401, "You don't have permission to access it.");
}
};
// add auth before protected routes.
for (String filter : filters) {
before(filter, f);
}
}
示例12: getMenu
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@RequestMapping(value = "/menu/getList",method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "獲取當前登錄用戶有權限的菜單")
public Object getMenu(){
// 已注冊係統
UpmsSystemExample upmsSystemExample = new UpmsSystemExample();
upmsSystemExample.createCriteria().andStatusEqualTo((byte) 1);
List<UpmsSystem> upmsSystems = upmsSystemService.selectByExample(upmsSystemExample);
// 當前登錄用戶權限
Subject subject = SecurityUtils.getSubject();
String username = (String) subject.getPrincipal();
UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
JSONArray jsonArr = new JSONArray();
for(UpmsSystem upmsSystem : upmsSystems) {
JSONObject rootNode = new JSONObject();
rootNode.put("name", upmsSystem.getSystemId());
rootNode.put("title", upmsSystem.getTitle());
rootNode.put("description", upmsSystem.getDescription());
rootNode.put("icon", upmsSystem.getIcon());
rootNode.put("order", upmsSystem.getOrders());
rootNode.put("basePath", upmsSystem.getBasepath());
rootNode.put("banner", upmsSystem.getBanner());
jsonArr.add(menuTreeFactory(rootNode,upmsPermissions, true));
}
return new UpmsResult(UpmsResultConstant.SUCCESS, jsonArr);
}
示例13: isAccessAllowed
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("驗證登陸信息==" + req.getRequestURI());
System.out.println("sessionId==" + req.getSession().getId());
Subject currentUser = SecurityUtils.getSubject();
if (null != currentUser) {
if (currentUser.isAuthenticated() || currentUser.isRemembered()) {
return true;
}
}
// 返回false表示不執行後續的過濾器
return false;
}
示例14: hasAnyRoles
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
/**
* 驗證用戶是否具有以下任意一個角色。
* @param roleNames 角色列表
* @return 用戶是否具有以下任意一個角色
*/
public boolean hasAnyRoles(Collection<String> roleNames) {
Subject subject = SecurityUtils.getSubject();
if (subject != null && roleNames != null) {
for (String role : roleNames) {
if (role != null && subject.hasRole(role.trim()) == true) {
return true;
}
}
}
return false;
}
示例15: login
import org.apache.shiro.SecurityUtils; //導入方法依賴的package包/類
@Transactional
@Override
public ResponseResult login(String ip, String account, String password, Boolean rememberMe) {
ResponseResult result = ResponseResult.createSuccessResult();
User user = findByAccount(account);
if (user == null) {
result.setCode(ResponseCode.ERROR).setMessage("登錄名不存在");
} else if (!user.getPassword().equals(password)) {
result.setCode(ResponseCode.ERROR).setMessage("密碼不正確");
} else if (!user.getIsEnable()) {
result.setCode(ResponseCode.ERROR).setMessage("已被管理員禁用");
} else {
// 是否允許多地登錄
String multLogin = settingsService.getValueByKey("mult_login");
// 判斷是否已登錄
boolean rs = userOnlineService.hasLogin(account);
// 不允許
if ("0".equals(multLogin)) {
// 是否允許多地登錄
String killLogin = settingsService.getValueByKey("kill_login");
// 不允許擠掉之前用戶登錄
if ("0".equals(killLogin)) {
// 判斷是否已經登錄
if (rs) {
result.setCode(ResponseCode.ERROR).setMessage("賬號已在另外一處地點登錄,請先下線再登錄");
return result;
}
}
// 踢出之前登錄用戶
if (rs) {
userOnlineService.kickoutByAccount(account);
}
}
// 登錄
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), password);
currentUser.login(token);// 登錄認證 記錄登陸信息
token.setRememberMe(rememberMe);
System.out.println("****登陸成功*****");
user.setLastLoginIp(ip);
user.setLoginCount(user.getLoginCount() + 1);
user.setLastLoginTime(new Date());
mapper.update(user);
// 記錄日誌
LoginLog log = new LoginLog();
log.setUserId(user.getAccount());
log.setLoginType((short) 1);
log.setLoginDesc("登錄成功");
log.setIpInfoCountry(null);
log.setIpInfoRegion(null);
log.setIpInfoCity(null);
log.setIpInfoIsp(null);
log.setLoginIp(ip);
log.setLoginTime(new Timestamp(new Date().getTime()));
// 保存登錄日誌
loginLogMapper.insert(log);
Session session = currentUser.getSession();
session.setAttribute("user", user);
session.setAttribute("userid", user.getAccount());
// session.setAttribute("kickout", false); // 標記是否下線
}
return result;
}