How to restrict access to the Spring MVC controller

Viewed 1875

I am writing a web service with an authorization and registration form. There are two types of users: regular and administrator. There is a controller that sends to the admin page at a given URL:

@Controller
public class ViewPageController {
    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String sendAdminPage(){
        return "AdminPage";
    }
}

But ordinary users can also access this page. It is necessary that only those who logged in as an administrator get to the admin page. There are options for how this can be organized? Maybe save the logged in user in the session? (Preferably without Spring Security)

1 Answers

the easy way define a Aspect and A annotation.some code like this

@Inherited
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorize {

//
String[] value() default {};

}

AuthorizationAspect.java

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class AuthorizationAspect {

private final AuthorizationService authorizationService;

private final CacheUtil cacheUtil;

private static final String PRE = "AUTH";

@Before("@annotation(com.jin.learn.config.security.Authorize)")
public void checkPermission(JoinPoint joinPoint) {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    Long accountId = JWTUtil.getUserIdFromRequest(request);
    Set<String> authorization = cacheUtil.getAllSet(PRE + accountId);
    if(authorization==null){
        authorization = authorizationService.findByAccountId(accountId);
        cacheUtil.save(PRE + accountId, authorization);
    }
    Authorize authorize = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(Authorize.class);
    String[] needAuthorization = authorize.value();
    if (needAuthorization.length == 0)  return;
    if (authorization!=null && !authorization.isEmpty()) {
        if (!authorization.containsAll(Arrays.asList(needAuthorization))){

            throw new SystemException(ExceptionCode.NO_PERMISSION);
        }
    } else {
        throw new SystemException(ExceptionCode.NO_PERMISSION);
    }
 }
}

use like this

@Authorize(value="needRight")
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String sendAdminPage(){
    return "AdminPage";
}

besides,there are some security framework shiro and spring-security

Related