如何在Spring MVC中逐屏申请权限?

huangapple go评论81阅读模式
英文:

how to apply screen by screen permisssion in Spring mvc?

问题

我是Spring MVC框架的初学者,正在构建一个应用程序,在这个应用程序中,我有一个角色,角色在不同的屏幕上具有不同的权限。例如:在仪表板上,用户有两个权限(读取和写入),而在第二个屏幕页面上,用户有(读取、写入和创建)权限。所以我想知道如何将这些权限与会话一起存储,以便在每个屏幕上检查权限时获取这些权限或者是否有其他更有效的方法来完成这个过程。

这是我在登录时的用户验证代码:

public String validate(String userName, String password, HttpServletResponse response, HttpServletRequest request, Model model) {
    logger.debug("Starting of the method validate");
    System.out.println("validate");

    Session session = null;

    try {
        AppConfig aapConfig = new AppConfig();
        List<UsersTable> userList = aapConfig.findAll(UsersTable.class);

        System.out.println("############userList length is " + userList.size());

        if (!userList.isEmpty()) {
            System.out.println("*****************UserList is not empty");
            Map<String, UsersTable> userMap = userList.stream().filter(e -> e.getUsername() != null)
                    .collect(Collectors.toMap(e -> e.getUsername(), e -> e, (x, y) -> x));

            if (userMap.containsKey(userName)) {
                UsersTable user = userMap.get(userName);
                if (StringUtils.equals(EncryptDecryptPassword.decrypt(user.getUserpassword(), "AirtelSiva"), password)) {
                    String userFullName = user.getUserfirstname();
                    String circleId = user.getUsercircle();
                    System.out.println("&&&&&&&&&&&&&& Circle ID is " + circleId);
                    HttpSession httpSession = request.getSession();
                    String id = httpSession.getId();
                    System.out.println(id);
                    httpSession.setAttribute("userFullName", userFullName);
                    httpSession.setAttribute("userName", userName);
                    httpSession.setAttribute("circleId", circleId);

                    // saving the userName with the unique session Id
                    UserSession userSession = new UserSession();
                    userSession.setUserName(userName);
                    userSession.setSessionId(id);
                    return "";
                }
            }
        }
    }

请注意,这只是代码的一部分,涉及用户验证和会话管理。要实现屏幕级别的权限管理,您需要在系统中定义角色、权限和屏幕,并在每个屏幕上根据用户的角色和权限来控制访问。如果需要更多关于权限管理的帮助,请提出具体的问题。

英文:

I am a beginner in spring MVC framework and I am building an application in which I have a role and role have different permissions on different screen .like:- on Dashboard user have two permissions (Read and write) and in second screen page user have (Read , Write and Create) permission.
so just want to know how could I put this permission with the session to get these in with the screen type at each screen when I am checking the permission or another method to do this process in a more effective way.

 this my user validation code at login time:- 
public String validate(String userName, String password, HttpServletResponse response, HttpServletRequest request,
Model model) {
logger.debug(&quot;Starting of the method validate&quot;);
System.out.println(&quot;validate&quot;);
Session session = null;
try {
AppConfig aapConfig = new AppConfig();
List&lt;UsersTable&gt; userList = aapConfig.findAll(UsersTable.class);
System.out.println(&quot;############userList length is &quot; +userList.size());
if (!userList.isEmpty()) {
System.out.println(&quot;*****************UserList is not emptry&quot;);
Map&lt;String, UsersTable&gt; userMap = userList.stream().filter(e -&gt; e.getUsername() != null)
.collect(Collectors.toMap(e -&gt; e.getUsername(), e -&gt; e, (x, y) -&gt; x));
if (userMap.containsKey(userName)) {
UsersTable user = userMap.get(userName);
if (StringUtils.equals(EncryptDecryptPassword.decrypt(user.getUserpassword(), &quot;AirtelSiva&quot;),
password)) {
String userFullName = user.getUserfirstname();
String circleId = user.getUsercircle();
System.out.println(&quot;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp; Circle ID is &quot;+circleId);
HttpSession httpSession =request.getSession();
String id = httpSession.getId();
System.out.println(id);
httpSession.setAttribute(&quot;userFullName&quot;, userFullName);
httpSession.setAttribute(&quot;userName&quot;, userName);
httpSession.setAttribute(&quot;circleId&quot;, circleId);
// saving the userName with the unique session Id
UserSession userSession = new UserSession();
userSession.setUserName(userName);
userSession.setSessionId(id);
return&quot;&quot;;
}

答案1

得分: 2

使用spring-security,您可以以最小的努力提供此授权。将所需的依赖项添加到您的POM并配置身份验证。请注意,在添加spring-security依赖项时,其版本应与您使用的spring版本兼容。

您可以简单地提供身份验证和授权,如下所示:

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure( AuthenticationManagerBuilder auth ) throws Exception
    {
     // 使用内存中的身份验证
        User.UserBuilder users = User.withDefaultPasswordEncoder();
        auth.inMemoryAuthentication()
            .withUser( users.username( "john" ).password( "john1234" ).roles( "READ", "WRITE" ) )
            .withUser( users.username( "doe" ).password( "doe1234" ).roles( "READ", "WRITE", "CREATE" ) );
    }

    /**
     * This allows adding custom login-form and add HTTP URL security
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure( HttpSecurity http ) throws Exception
    {
        http.authorizeRequests()
            .antMatchers( "/").permitAll()
            .antMatchers( "/dashboard" ).hasAnyRole( "READ","WRITE" )
            .antMatchers( "/anotherPage" ).hasAnyRole( "READ","WRITE","CREATE" )
            .anyRequest()
            .authenticated()
            .and()
            .formLogin() // Add form login
            .loginPage( "/showMyLoginPage" ) // Pointing to custom login form. This line is optional as spring by default provides a login page
            .loginProcessingUrl( "/authenticateTheUser" ) // No coding needed. Just provide some endpoint. You need not implement this endpoint. Spring will take care of it.
            .permitAll()
            // Other necessary validations like CSRF or cookie policy
    }
}

请在spring官方文档的这里找到教程。

在使用Spring-security进行授权后,您可以要求模板引擎[如果支持]根据已登录用户的角色显示或隐藏页面的特定部分。

作为示例,以下是如何在JSP中基于用户角色隐藏链接的方法,通过添加类似<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>的安全支持。

在这里,只有拥有ADMIN角色的用户才能看到此链接。

<security:authorize access="hasRole('ADMIN')">
<hr>
<p><a href="${pageContext.request.contextPath}/admin">Link to admin page</a> ( Only admin can see this )</p>
<hr>
</security:authorize>

这个链接包含了开始使用spring-security所需的所有详细信息。

英文:

With spring-security, you can provide this authorization with minimal effort. Add the required dependencies to your POM and configure the authentication. Keep in mind, when adding the spring-security dependency, its version should be compatible with the spring version you are using.

You can simply provide authentication and authorization like

@Configuration
@EnableWebSecurity
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception
{
// Using in-memory authentication
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser( users.username( &quot;john&quot; ).password( &quot;john1234&quot; ).roles( &quot;READ&quot;, &quot;WRITE&quot; ) )
.withUser( users.username( &quot;doe&quot; ).password( &quot;doe1234&quot; ).roles( &quot;READ&quot;, &quot;WRITE&quot;, &quot;CREATE&quot; ) );
}
/**
* This allows adding custom login-form and add HTTP URL security
*
* @param http
* @throws Exception
*/
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.authorizeRequests()
.antMatchers( &quot;/&quot; ).permitAll()
.antMatchers( &quot;/dashboard&quot; ).hasAnyRole( &quot;READ&quot;,&quot;WRITE&quot; )
.antMatchers( &quot;/anotherPage&quot; ).hasAnyRole( &quot;READ&quot;,&quot;WRITE&quot;,&quot;CREATE&quot; )
.anyRequest()
.authenticated()
.and()
.formLogin() // Add form login
.loginPage( &quot;/showMyLoginPage&quot; ) // Pointing to custom login form. This line is optional as spring by default provides a login page
.loginProcessingUrl( &quot;/authenticateTheUser&quot; ) // No coding needed. Just provide some endpoint. You need not implement this endpoint. Spring will take care of it.
.permitAll()
// Other necessary validations like CSRF or cookie policy
}

Please find the tutorial on the spring official doc here.

And once you do the authorization with Spring-security. You can ask your template engine [if it support]. to show or hide certain sections of the page depending on the roles of the logged user.

As an example, here's how you could hide a link based on the user role in JSP by adding the security support like &lt;%@ taglib prefix=&quot;security&quot; uri=&quot;http://www.springframework.org/security/tags&quot; %&gt;

Here, only users having role ADMIN can see this link.

&lt;security:authorize access=&quot;hasRole(&#39;ADMIN&#39;)&quot;&gt;
&lt;hr&gt;
&lt;p&gt;&lt;a href=&quot;${pageContext.request.contextPath}/admin&quot;&gt;Link to admin page&lt;/a&gt; ( Only admin can see this )&lt;/p&gt;
&lt;hr&gt;
&lt;/security:authorize&gt;

This link contain all the necessary detail to get started on spring-security.

huangapple
  • 本文由 发表于 2020年5月4日 14:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61586552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定