本文整理汇总了Java中org.apache.shiro.subject.Subject类的典型用法代码示例。如果您正苦于以下问题:Java Subject类的具体用法?Java Subject怎么用?Java Subject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Subject类属于org.apache.shiro.subject包,在下文中一共展示了Subject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getSession
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
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;
}
示例2: authorize
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
public void authorize(ResourcePermission context) {
Subject currentUser = getSubject();
if (currentUser == null) {
return;
}
if (context == null) {
return;
}
if (context.getResource() == Resource.NULL && context.getOperation() == Operation.NULL) {
return;
}
try {
currentUser.checkPermission(context);
} catch (ShiroException e) {
String msg = currentUser.getPrincipal() + " not authorized for " + context;
logger.info(msg);
throw new NotAuthorizedException(msg, e);
}
}
示例3: login
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@ModelAttribute("login")
private MsgTO login(@RequestBody MsgTO msgTo) {
Long userId = msgTo.getUserId();
String password = msgTo.getPassword();
SysUserEntity user = ((SysUserService) SpringContextUtils.getBean("sysUserService")).queryObject(userId);
if(user==null){
throw new RRException("用户id不存在");
}
try {
Subject subject = ShiroUtils.getSubject();
// sha256加密
password = new Sha256Hash(password).toHex();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password);
subject.login(token);
} catch (Exception e) {
throw new RRException("登录失败");
}
msgTo.setUser(user);
return msgTo;
}
示例4: testIniAuthorization
import org.apache.shiro.subject.Subject; //导入依赖的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);
}
示例5: onLoginSuccess
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
/**
* 覆盖默认实现,用sendRedirect直接跳出框架,以免造成js框架重复加载js出错。
*
* @param token
* @param subject
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
protected boolean onLoginSuccess(AuthenticationToken token,
Subject subject, ServletRequest request, ServletResponse response)
throws Exception {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (!"XMLHttpRequest".equalsIgnoreCase(httpRequest
.getHeader("X-Requested-With"))) {
httpResponse.sendRedirect(httpRequest.getContextPath()
+ this.getSuccessUrl());
} else {
httpRequest.getRequestDispatcher("/CN").forward(httpRequest,
httpResponse);
}
return false;
}
示例6: checkSubjectRolesAndPermissions
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
/**
* Check subject roles and permissions.
*
* @param currentUser the current user
* @throws FailedLoginException the failed login exception in case roles or permissions are absent
*/
protected void checkSubjectRolesAndPermissions(final Subject currentUser) throws FailedLoginException {
if (this.requiredRoles != null) {
for (final String role : this.requiredRoles) {
if (!currentUser.hasRole(role)) {
throw new FailedLoginException("Required role " + role + " does not exist");
}
}
}
if (this.requiredPermissions != null) {
for (final String perm : this.requiredPermissions) {
if (!currentUser.isPermitted(perm)) {
throw new FailedLoginException("Required permission " + perm + " does not exist");
}
}
}
}
示例7: showTagBody
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@Override
protected boolean showTagBody(String permissionNames) {
boolean hasAnyPermission = false;
Subject subject = getSubject();
if (subject != null) {
// Iterate through permissions and check to see if the user has one of the permissions
for (String permission : permissionNames.split(PERMISSION_NAMES_DELIMETER)) {
if (subject.isPermitted(permission.trim())) {
hasAnyPermission = true;
break;
}
}
}
return hasAnyPermission;
}
示例8: login
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView login(User user, String captcha, HttpSession session,HttpServletRequest request) throws Exception{
ModelAndView mv = new ModelAndView();
String kaptchaExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
System.out.println(kaptchaExpected);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
try{
subject.login(token);
mv.setViewName("redirect:/index.jsp");
} catch (AuthenticationException e){
mv.addObject("message", "login errors");
mv.setViewName("redirect:/backend/login");
}
return mv;
}
示例9: getGroups
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@ApiOperation("获取小组列表")
@GetMapping
public ResponseEntity getGroups(@RequestParam("page") int page,
@RequestParam("page_size") int pageSize,
@RequestParam(name = "owner", required = false, defaultValue = "0") int owner) {
if (owner > 0) {
// 鉴权
Subject subject = SecurityUtils.getSubject();
if (! subject.isAuthenticated()) {
throw new UnauthorizedException();
}
int uid = SessionHelper.get().getUid();
if (uid != owner) {
throw new UnauthorizedException();
}
PageRowBounds pager = new PageRowBounds(page, pageSize);
List<GroupEntity> groups = groupService.getGroups(uid, pager);
Map<String, Object> data = new HashMap<>(2);
data.put("data", groups);
data.put("total", pager.getTotal());
return new ResponseEntity(data);
} else {
return new ResponseEntity(new ArrayList<>());
}
}
示例10: deleteTag
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
public void deleteTag(String tag) {
String refName = GitUtils.tag2ref(tag);
ObjectId commitId = getRevCommit(refName).getId();
try {
git().tagDelete().setTags(tag).call();
} catch (GitAPIException e) {
throw new RuntimeException(e);
}
Subject subject = SecurityUtils.getSubject();
GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
@Override
public void run() {
ThreadContext.bind(subject);
try {
Project project = GitPlex.getInstance(ProjectManager.class).load(getId());
GitPlex.getInstance(ListenerRegistry.class).post(
new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
} finally {
ThreadContext.unbindSubject();
}
}
});
}
示例11: logout
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
public void logout() {
Subject currentUser = getSubject();
if (currentUser == null) {
return;
}
try {
logger.info("Logging out " + currentUser.getPrincipal());
currentUser.logout();
} catch (ShiroException e) {
logger.info(e.getMessage(), e);
throw new GemFireSecurityException(e.getMessage(), e);
}
// clean out Shiro's thread local content
ThreadContext.remove();
}
示例12: responseApprovalDeny
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
protected void responseApprovalDeny() throws IOException, OAuthSystemException {
final OAuthResponse oAuthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
.setError(OAuthError.CodeResponse.ACCESS_DENIED)
.setErrorDescription("User denied access")
.location(clientDetails().getRedirectUri())
.setState(oauthRequest.getState())
.buildQueryMessage();
LOG.debug("'ACCESS_DENIED' response: {}", oAuthResponse);
WebUtils.writeOAuthQueryResponse(response, oAuthResponse);
//user logout when deny
final Subject subject = SecurityUtils.getSubject();
subject.logout();
LOG.debug("After 'ACCESS_DENIED' call logout. user: {}", subject.getPrincipal());
}
示例13: onPreHandle
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String authzHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
if (authzHeader != null) {
if (authzHeader.toLowerCase(Locale.ENGLISH).startsWith("basic")
|| authzHeader.toLowerCase(Locale.ENGLISH).startsWith("token")) {
String authToken = StringUtils.substringAfter(authzHeader, " ");
String decoded = Base64.decodeToString(authToken);
String userName = StringUtils.substringBefore(decoded, ":").trim();
String password = StringUtils.substringAfter(decoded, ":").trim();
if (userName.length() != 0 && password.length() != 0) {
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
subject.login(token);
}
}
}
}
return true;
}
示例14: onAccessDenied
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@Override
protected boolean onAccessDenied(ServletRequest request,
ServletResponse response) throws Exception {
Subject subject = getSubject(request, response);
if (null == subject.getPrincipal()) {//表示没有登录,重定向到登录页面
saveRequest(request);
WebUtils.issueRedirect(request, response, ShiroUtils.LOGIN_URL);
} else {
if(ShiroUtils.isAjax(request)){
Map<String, Object> result = new HashMap<String, Object>();
result.put("status", "401");
result.put("message", "sorry,您没有权限");
result.put("url", ShiroUtils.UNAUTHORIZED);
ShiroUtils.writeJson(response, result);
}else
{
if (StringUtils.hasText(ShiroUtils.UNAUTHORIZED)) {//如果有未授权页面跳转过去
WebUtils.issueRedirect(request, response, ShiroUtils.UNAUTHORIZED);
} else {//否则返回401未授权状态码
WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
return Boolean.FALSE;
}
示例15: signin
import org.apache.shiro.subject.Subject; //导入依赖的package包/类
@RequestMapping(value = "/signin", method = {
RequestMethod.POST})
public String signin(ModelMap map, User user, HttpServletRequest request) {
String error;
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPasswd());
token.setRememberMe(null != request.getParameter("rememberme") ? true : false);
try {
Subject subject = SecurityUtils.getSubject();
subject.login(token);
subject.getSession().setAttribute("curUser", userService.findByUsername((String) subject.getPrincipal()));
return "redirect:/dashboard/console";
} catch (UnknownAccountException uae) {
error = "用户名错误!";
} catch (IncorrectCredentialsException ice) {
error = "密码错误!";
} catch (LockedAccountException lae) {
error = "用户被锁定!";
}
map.addAttribute("error", error);
return "signin";
}