首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用Spring安全保护Vaadin流应用程序

如何用Spring安全保护Vaadin流应用程序
EN

Stack Overflow用户
提问于 2018-10-29 16:41:56
回答 1查看 4.8K关注 0票数 6

我正在尝试将vaadin 10与spring安全性集成(使用vaadin提供的spring项目库),我对它们如何准确地交互感到困惑。如果我转到受保护的url (在本例中是"/about"),直接在浏览器中输入它,就会显示登录页面。如果我通过单击UI中的链接转到同一个URL,即使我没有经过身份验证,页面也会显示出来。因此,我猜想Vaadin并没有通过Security的过滤链,但是我如何在UI中保护我的资源,以及如何在vaadin和spring之间共享经过身份验证的用户?我应该实现两次安全吗?可用的文档似乎没有涵盖这一点,而且互联网上的每个链接都有Vaadin7-8的例子,我从未使用过这些例子,并且似乎与10+不同。

有没有人知道这方面的任何资源,或者你能告诉我这一切是如何一起工作的,这样我才能知道我在做什么?

以下是我的安全配置:

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] ALLOWED_GET_URLS = {
        "/",
        //"/about",
        "/login/**",
        "/frontend/**",
        "/VAADIN/**",
        "/favicon.ico"
    };

    private static final String[] ALLOWED_POST_URLS = {
        "/"
    };

    //@formatter:off
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .mvcMatchers(HttpMethod.GET, ALLOWED_GET_URLS)
                    .permitAll()
                .mvcMatchers(HttpMethod.POST, ALLOWED_POST_URLS)
                    .permitAll()
                .anyRequest()
                    .fullyAuthenticated()
             .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
            .and()
                .logout()
                    .logoutSuccessUrl("/")
                    .permitAll();
    }
    //@formatter:on

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-05 05:44:36

使用Vaadin (12.0.2)、Spring (2.0.2.RELEASE)和Security,基本上可以通过以下方式获得基于角色/权限的授权;

基于路由/上下文的角色/权限管理

  • 弹簧安全(HttpSecurity)
  • Vaadin (BeforeEnterListener和路由/导航API)

业务单元角色/权限管理

  • 在代码中使用HttpServletRequest.isUserInRole方法

让我们从一个Spring安全配置的简单示例开始;

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
public class WebSecurityConfig
        extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable() // CSRF is handled by Vaadin: https://vaadin.com/framework/security
                .exceptionHandling().accessDeniedPage("/accessDenied")
                .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
                .and().logout().logoutSuccessUrl("/")
                .and()
                .authorizeRequests()
                // allow Vaadin URLs and the login URL without authentication
                .regexMatchers("/frontend/.*", "/VAADIN/.*", "/login.*", "/accessDenied").permitAll()
                .regexMatchers(HttpMethod.POST, "/\\?v-r=.*").permitAll()
                // deny any other URL until authenticated
                .antMatchers("/**").fullyAuthenticated()
            /*
             Note that anonymous authentication is enabled by default, therefore;
             SecurityContextHolder.getContext().getAuthentication().isAuthenticated() always will return true.
             Look at LoginView.beforeEnter method.
             more info: https://docs.spring.io/spring-security/site/docs/4.0.x/reference/html/anonymous.html
             */
        ;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin").password("$2a$10$obstjyWMAVfsNoKisfyCjO/DNfO9OoMOKNt5a6GRlVS7XNUzYuUbO").roles("ADMIN");// user and pass: admin 
    }

    /**
    * Expose the AuthenticationManager (to be used in LoginView)
    * @return
    * @throws Exception
    */
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

正如您所看到的,我还没有根据我的任何路由视图(带@Route注解)上的角色指定任何权限。我要做的是,如果我有一个路由视图,我将注册一个BeforeEnterListener当它(路由视图)正在构建,并将检查所需的角色/特权在那里。

下面是一个示例,用于在导航到admin-utils视图之前检查用户是否具有管理角色;

代码语言:javascript
复制
@Route(value = "admin-utils")
public class AdminUtilsView extends VerticalLayout { 
@Autowired
private HttpServletRequest req;
...
    AdminUtilsView() {
        ...
        UI.getCurrent().addBeforeEnterListener(new BeforeEnterListener() {
            @Override
            public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
                if (beforeEnterEvent.getNavigationTarget() != DeniedAccessView.class && // This is to avoid a
                        // loop if DeniedAccessView is the target
                        !req.isUserInRole("ADMIN")) {
                    beforeEnterEvent.rerouteTo(DeniedAccessView.class);
                }
            }
        });
    }
}

如果用户没有管理角色,他将被路由到DeniedAccessView,这在Security配置中已经是允许的。

代码语言:javascript
复制
@Route(value = "accessDenied")
public class DeniedAccessView
        extends VerticalLayout {
    DeniedAccessView() {
        FormLayout formLayout = new FormLayout();
        formLayout.add(new Label("Access denied!"));
        add(formLayout);
    }
}

在上面的示例(AdminUtilsView )中,您还可以通过自动装配HttpServletRequest.isUserInRole()来看到HttpServletRequest()在Vaadin代码中的用例。

摘要:如果视图有一个路由,那么首先使用BeforeEnterListener来授权请求,否则使用Security (例如regexMatchers或antMatchers)进行rest服务等等。

注意:在同一个规则中同时使用Vaadin和Security规则的可能有点扭曲,我并不认为(它会导致Vaadin中的一些内部循环;例如,假设我们有一个使用/view路由的视图,以及SpringSecurityfor/view中的一个条目,其中包含一个必需的角色)。如果用户缺少这样的角色,并且他被路由/导航到这样的页面(使用Vaadin路由API),Vaadin尝试打开与路由相关的视图,而Spring安全则避免了由于缺少角色而导致的情况。

另外,我认为使用Vaadin导航API在重新路由用户或将用户导航到不同的视图/上下文之前的一个良好做法是检查所需的角色/权限。

另外,为了给出一个在Vaadin中使用AuthenticationManager的例子,我们可以有一个类似于Vaadin的基于Vaadin的LoginView;

代码语言:javascript
复制
@Route(value = "login")
public class LoginView
        extends FlexLayout implements BeforeEnterObserver {

    private final Label label;
    private final TextField userNameTextField;
    private final PasswordField passwordField;

    /**
    * AuthenticationManager is already exposed in WebSecurityConfig
    */
    @Autowired
    private AuthenticationManager authManager;

    @Autowired
    private HttpServletRequest req;

    LoginView() {
        label = new Label("Please login...");

        userNameTextField = new TextField();
        userNameTextField.setPlaceholder("Username");
        UiUtils.makeFirstInputTextAutoFocus(Collections.singletonList(userNameTextField));

        passwordField = new PasswordField();
        passwordField.setPlaceholder("Password");
        passwordField.addKeyDownListener(Key.ENTER, (ComponentEventListener<KeyDownEvent>) keyDownEvent -> authenticateAndNavigate());

        Button submitButton = new Button("Login");
        submitButton.addClickListener((ComponentEventListener<ClickEvent<Button>>) buttonClickEvent -> {
            authenticateAndNavigate();
        });

        FormLayout formLayout = new FormLayout();
        formLayout.add(label, userNameTextField, passwordField, submitButton);
        add(formLayout);

        // center the form
        setAlignItems(Alignment.CENTER);
        this.getElement().getStyle().set("height", "100%");
        this.getElement().getStyle().set("justify-content", "center");
    }

    private void authenticateAndNavigate() {
        /*
        Set an authenticated user in Spring Security and Spring MVC
        spring-security
        */
        UsernamePasswordAuthenticationToken authReq
                = new UsernamePasswordAuthenticationToken(userNameTextField.getValue(), passwordField.getValue());
        try {
            // Set authentication
            Authentication auth = authManager.authenticate(authReq);
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(auth);

            /*
            Navigate to the requested page:
            This is to redirect a user back to the originally requested URL – after they log in as we are not using
            Spring's AuthenticationSuccessHandler.
            */
            HttpSession session = req.getSession(false);
            DefaultSavedRequest savedRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
            String requestedURI = savedRequest != null ? savedRequest.getRequestURI() : Application.APP_URL;

            this.getUI().ifPresent(ui -> ui.navigate(StringUtils.removeStart(requestedURI, "/")));
        } catch (BadCredentialsException e) {
            label.setText("Invalid username or password. Please try again.");
        }
    }

    /**
    * This is to redirect user to the main URL context if (s)he has already logged in and tries to open /login
    *
    * @param beforeEnterEvent
    */
    @Override
    public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        //Anonymous Authentication is enabled in our Spring Security conf
        if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) {
            //https://vaadin.com/docs/flow/routing/tutorial-routing-lifecycle.html
            beforeEnterEvent.rerouteTo("");
        }
    }
}

最后,下面是可以从菜单或按钮调用的注销方法:

代码语言:javascript
复制
/**
 * log out the current user using Spring security and Vaadin session management
 */
void requestLogout() {
    //https://stackoverflow.com/a/5727444/1572286
    SecurityContextHolder.clearContext();
    req.getSession(false).invalidate();

    // And this is similar to how logout is handled in Vaadin 8:
    // https://vaadin.com/docs/v8/framework/articles/HandlingLogout.html
    UI.getCurrent().getSession().close();
    UI.getCurrent().getPage().reload();// to redirect user to the login page
}

通过查看以下示例,您可以继续使用完成角色管理并创建一个PasswordEncoder bean:

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53050125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档