Spring Security – Run-As Authentication – Spring Security – Run-As Authentication

最后修改: 2016年 5月 17日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll illustrate how to use Run-As authentication in Spring Security with a simple scenario.

在本教程中,我们将通过一个简单的场景说明如何在Spring Security中使用Run-As认证。

The very high-level explanation about Run-As is as follows: a user can execute some piece of logic as another principal with different privileges.

关于Run-As的非常高层次的解释如下:一个用户可以作为另一个具有不同权限的委托人执行一些逻辑。

2. The RunAsManager

2、RunAsManager

The first thing we’ll need to do is set up our GlobalMethodSecurity and inject a RunAsManager.

我们需要做的第一件事是设置我们的GlobalMethodSecurity并注入一个RunAsManager

This is responsible for providing the temporary Authentication object with extra privileges:

这负责为临时Authentication对象提供额外的权限。

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected RunAsManager runAsManager() {
        RunAsManagerImpl runAsManager = new RunAsManagerImpl();
        runAsManager.setKey("MyRunAsKey");
        return runAsManager;
    }
}

By overriding runAsManager, we’re replacing the default implementation in the base class – which simply returns a null.

通过重写runAsManager,我们取代了基类中的默认实现–它只是返回一个null

Also notice the key property – the framework uses that to secure/verify temporary Authentication objects (created via this manager).

还注意到key属性–框架使用它来保护/验证临时Authentication对象(通过该管理器创建)。

Finally – the resulting Authentication object is a RunAsUserToken.

最后–产生的Authentication对象是一个RunAsUserToken

3. Security Configuration

3.安全配置

To authenticate our temporary Authentication object, we’ll set up a RunAsImplAuthenticationProvider:

为了验证我们的临时Authentication对象,我们将设置一个RunAsImplAuthenticationProvider

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    ...
    auth.authenticationProvider(runAsAuthenticationProvider());
}

@Bean
public AuthenticationProvider runAsAuthenticationProvider() {
    RunAsImplAuthenticationProvider authProvider = new RunAsImplAuthenticationProvider();
    authProvider.setKey("MyRunAsKey");
    return authProvider;
}

We’re of course setting this up with the same key we used in the manager – so that the provider can check that the RunAsUserToken authentication object is created using the same key.

我们当然要用我们在管理器中使用的相同的密钥来设置它–这样提供者就可以检查RunAsUserToken认证对象是用相同的密钥创建的。

4. The Controller With @Secured

4.带有@Secured的控制器

Now – let’s see how to use Run-As Authentication replacement:

现在–让我们看看如何使用Run-As认证替换。

@Controller
@RequestMapping("/runas")
class RunAsController {

    @Secured({ "ROLE_USER", "RUN_AS_REPORTER" })
    @RequestMapping
    @ResponseBody
    public String tryRunAs() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return "Current User Authorities inside this RunAS method only " + 
          auth.getAuthorities().toString();
    }

}

The core thing here is the new role – RUN_AS_REPORTER. This is the trigger of the Run-As functionality – as the framework deals with it differently because of the prefix.

这里的核心是新的角色 – RUN_AS_REPORTER。这是Run-As功能的触发器–因为框架因为前缀的关系而对它的处理不同。

When a request executes through this logic, we’ll have:

当一个请求通过这个逻辑执行时,我们会有。

  • The current user authorities before tryRunAs() method are [ROLE_USER]
  • The current user authorities inside tryRunAs() method are [ROLE_USER, ROLE_RUN_AS_REPORTER]
  • The temporary Authentication object replaces the existing Authentication object for the duration of the tryRunAS() method invocation only

5. The Service

5.服务

Finally, let’s implement the actual logic – a simple service layer that’s also secured:

最后,让我们来实现实际的逻辑–一个简单的服务层,也是安全的。

@Service
public class RunAsService {

    @Secured({ "ROLE_RUN_AS_REPORTER" })
    public Authentication getCurrentUser() {
        Authentication authentication = 
          SecurityContextHolder.getContext().getAuthentication();
        return authentication;
    }
}

Note that:

请注意,。

  • To access getCurrentUser() method, we need to ROLE_RUN_AS_REPORTER
  • So we can only call getCurrentUser() method inside our tryRunAs() controller method

6. The Front-End

6.前端

Next, we will use a simple front-end to test our Run-As feature:

接下来,我们将使用一个简单的前端来测试我们的Run-As功能。

<html>
<body>
Current user authorities: 
    <span sec:authentication="principal.authorities">user</span>
<br/>
<span id="temp"></span>
<a href="#" onclick="tryRunAs()">Generate Report As Super User</a>
             
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function tryRunAs(){
    $.get( "/runas" , function( data ) {
         $("#temp").html(data);
    });
}
</script>
</body>
</html>

So now, when a user triggers the “Generate Report As Super User” action – they’ll obtain the temporary ROLE_RUN_AS_REPORTER authority.

因此,现在,当用户触发”以超级用户身份生成报告“动作时 – 他们将获得临时的ROLE_RUN_AS_REPORTER权限。

7. Conclusion

7.结论

In this quick tutorial, we explored a simple example using the Spring Security Run-As authentication replacement feature.

在这个快速教程中,我们探讨了一个使用 Spring Security Run-As 身份验证替换功能的简单示例。

This tutorial is based on the codebase available on GitHub.

本教程以GitHub上提供的代码库为基础