为特定网址添加密码保护

时间:2017-04-17 12:47:36

标签: java spring-boot spring-security

我有我的spring安全配置文件,如

package com.wi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import com.wi.HttpAuthenticationEntryPoint;
import com.wi.filter.AuthenticationFilter;
import com.wi.HttpLogoutSuccessHandler;
import com.wi.LogOutHandler;

/**
 * Web security configuration class
 */
@Configuration
@EnableWebSecurity
@Order( SecurityProperties.ACCESS_OVERRIDE_ORDER )
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private static final Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

@Autowired
private HttpAuthenticationEntryPoint authenticationEntryPoint;

@Autowired
private HttpLogoutSuccessHandler logoutSuccessHandler;

@Autowired
private MessageBundleResource messageBundle;

@Autowired
private LogOutHandler logoutHandler;

@Override
protected void configure( final HttpSecurity http ) throws DataException
{
    try
    {
        http.csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and().headers()
                .cacheControl().and()
                .addHeaderWriter(
                        new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
                .and().authorizeRequests()
                // Allow anonymous resource requests
                .antMatchers("/").permitAll().antMatchers("/login").permitAll().antMatchers("/pages/**").permitAll()
                // Allow anonymous logins
                .antMatchers("/auth/**").permitAll()

                // Allow test rest
                .antMatchers("/rest-test/**").permitAll()

                // Allow invite admin
                .antMatchers("/rest/user/inviteAdmin").permitAll()

                // Allow activate user
                .antMatchers("/rest/user/activateUser").permitAll()
                // Allow activate admin
                .antMatchers("/rest/user/activateAdmin").permitAll()

                // Allow check domain availability
                .antMatchers("/rest/user/checkDomainAvailability").permitAll()

                // Allow check company and email active
                .antMatchers("/rest/company/checkEmailAndCompanyIsActive").permitAll()

                // Allow check domain by email
                .antMatchers("/rest/user/getDomainByEmail").permitAll()

                // Allow reset password
                .antMatchers("/rest/user/resetPassword").permitAll()

                // Allow to get messages
                .antMatchers("/rest/kat/getMessages").permitAll()
                // upload
                .antMatchers("/rest/file/upload").permitAll()

                // Allow get user details
                .antMatchers("/rest/user/getUserDetails").permitAll()

                // Allow to get password pattern
                .antMatchers("/rest/config/getPasswordPattern").permitAll()

                .antMatchers("/rest/task/getCategories").permitAll()

                // Allow to get config messages
                .antMatchers("/rest/config/getTooltip").permitAll()
                // Allow to get webhook
                .antMatchers("/rest/integration/jiraWebHook").permitAll()
                // Allow to get global navigation
                .antMatchers("/rest/config/getGlobalNavigation").permitAll()

                .antMatchers("/rest/task/updateTaskDetail").permitAll()

                .antMatchers("/rest/task/updateTask").permitAll().antMatchers("/error/**").permitAll()
                // All other request need to be authenticated
                .antMatchers("/rest/**").authenticated().and().formLogin().loginPage("/login").permitAll().and()
                .logout().addLogoutHandler(logoutHandler).invalidateHttpSession(true)
                .logoutSuccessHandler(logoutSuccessHandler).logoutUrl("/rest/session/logout").and()

                // Custom Token based authentication based on the header
                // previously given to the client
                .addFilterBefore(new AuthenticationFilter(authenticationManager()),
                        BasicAuthenticationFilter.class);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).sessionFixation()
                .changeSessionId();

    }
    catch( final Exception e )
    {
        logger.error("Error", e);
        throw new DataException(StringConstants.EXCEPTION,
                messageBundle.getMessage("kat.error.something.went.wrong"), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

/**
 *
 * @param auth
 */
@Autowired
public void configureGlobal( final AuthenticationManagerBuilder auth )
{
    auth.authenticationProvider(domainUsernamePasswordAuthenticationProvider());

}

/**
 *
 * @return
 */
@Bean
public AuthenticationProvider domainUsernamePasswordAuthenticationProvider()
{
    return new UsernamePasswordAuthProvider();
}

}

如何在用户点击网址http://localhost:8080/swagger-ui.html时提示用户输入用户ID和密码。所有人都可以直接访问具有呼叫permitAll()的URL。但是,当用户点击http://localhost:8080/swagger-ui.html时,我希望spring告诉他用户ID和密码。怎么做?

1 个答案:

答案 0 :(得分:1)

你有很多配置。基本上,如果您应用了httpBasic或formLogin安全性,那么未被忽略或不允许所有的每个ant匹配器都将受到安全保护。

例如来自春季文件:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()                                                                1
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                  2
            .antMatchers("/admin/**").hasRole("ADMIN")                                      3
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            4
            .anyRequest().authenticated()                                                   5
            .and()
        // ...
        .formLogin();
}

如果网址以“/ resources /”开头,等于“/ signup”或等于“/ about”,则任何用户都可以访问请求

任何其他路径都会触发formLogin身份验证