标签: spring-security

弹簧安全403错误

我正在尝试按照网络指南使用Spring安全保护我的网站.所以在我的服务器端,WebSecurityConfigurerAdapter和控制器看起来像这样

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
implements ApplicationContextAware {

@Override
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
authManagerBuilder.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMI N");
}
}

@Controller
//@RequestMapping("/course")
public class CourseController implements ApplicationContextAware{

@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json")
public @ResponseBody List<Course> get(// The critirion used to find.
@RequestParam(value="what", required=true) String what,
@RequestParam(value="value", required=true) String value) {
//.....
}

@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public List<Course> upload(@RequestBody Course[] cs) {
}
}
Run Code Online (Sandbox Code Playgroud)

令我困惑的是服务器没有响应POST/DELETE方法,而GET方法工作正常.顺便说一下,我在客户端使用RestTemplate.例外情况是:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-security

39
推荐指数
4
解决办法
6万
查看次数

spring security:NoSuchBeanDefinitionException:找不到[org.springframework.security.config.annotation.ObjectPostProcessor]类型的限定bean

我正在尝试为我的其他应用添加spring-security.我在春季网站上按照教程(https://spring.io/guides/tutorials/spring-security-and-angular-js/)进行操作,但它使用了我不想使用的spring-boot组件,也许问题在这里.

我的安全配置在这里:

@Configuration
@Order(2147483636)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests()
            .antMatchers("/rest", "/").permitAll().anyRequest()
            .authenticated().and().csrf()
            .csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}

private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                    .getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security

39
推荐指数
5
解决办法
4万
查看次数

Spring Security - 需要403错误,而不是重定向

我正在使用Spring Security 3.0.4.我有一堆受Spring Security保护的Web服务.当我以未经身份验证的用户身份访问它们时,Spring Security会重定向到登录页面.而不是那样,我想返回HTTP 403错误.我怎样才能做到这一点?

这是我的安全配置:

<http auto-config="false" use-expressions="true" >

    <intercept-url pattern="/authorization.jsp" access="permitAll"/>
    <intercept-url pattern="/registration.jsp" access="permitAll"/>
    <intercept-url pattern="/api/authorization/auth" access="permitAll"/>
    <intercept-url pattern="/api/authorization/new" access="permitAll"/>
    <intercept-url pattern="/api/accounts/new" access="permitAll"/>
    <intercept-url pattern="/app/**" access="permitAll"/>
    <intercept-url pattern="/extjs/**" access="permitAll"/>

    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

    <form-login login-page="/authorization.jsp"
            default-target-url="/index.jsp"
            authentication-failure-url="/registration.jsp?login_error=1"
            always-use-default-target="true"
            />

    <logout logout-success-url="/authorization.jsp"
            logout-url="/j_spring_security_logout"
            invalidate-session="true"/>        

</http>
Run Code Online (Sandbox Code Playgroud)

spring spring-security

38
推荐指数
4
解决办法
2万
查看次数

如何使用Spring Security重新加载用户更新的权限

我正在使用Spring Security通过OpenID进行身份验证的应用程序.当用户登录时,会话中会加载某些权限.

我拥有完全权限的用户,可以修改其他用户的权限(撤销,添加角色).我的问题是,如何动态更改用户会话权限?(不能使用SecurityContextHolder,因为我想更改另一个用户会话).

简单方法:使用户会话无效,但如何?更好的方法:刷新用户会话与新权限,但如何?

java spring spring-security

38
推荐指数
4
解决办法
3万
查看次数

替代GrantedAuthorityImpl()类

我想要GrantedAuthorityImpl()类的替代方法.我希望在spring安全实现中使用它.GrantedAuthorityImpl()类是Depricated.hence我想要它的替代解决方案.

我的代码:

public Collection<GrantedAuthority> getAuthorities(Integer access) {
    List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

    if (access.compareTo(1) == 0) {
        authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
    }
    else{
        authList.add(new GrantedAuthorityImpl("ROLE_USER"));
    }
    return authList;
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security

38
推荐指数
1
解决办法
2万
查看次数

为什么在Spring Security中对'anonymousUser'进行身份验证?

这是我的主控制器:

package org.demian.demibox.controllers;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MainController {
    private String getUsername() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth.isAuthenticated())
            return auth.getName();
        else
            return null;
    }
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showHome() {
        String username = getUsername();
        System.out.println(username);
        if (username == null || username.length() == 0)
            return "welcome";
        return "index";
    }
}
Run Code Online (Sandbox Code Playgroud)

即使我没有登录,也auth.isAuthenticated()总是返回true.这是为什么?何时会auth.isAuthenticated()返回虚假?经过身份验证的用户的名称是,anonymousUser如果我没有登录,并且如果我已登录,则使用用户名.

编辑

这是我的security-context.xml档案:

<?xml version="1.0" encoding="UTF-8"?>
<beans …
Run Code Online (Sandbox Code Playgroud)

authentication spring spring-security java-ee

38
推荐指数
1
解决办法
4万
查看次数

Spring安全性:添加"成功登录事件监听器"

我是Spring Security的新手.如何添加将在用户成功登录时调用的事件侦听器?此外,我需要在此侦听器中获取某种唯一的会话ID,该ID应该可以进一步使用.我需要此ID与另一台服务器同步.

login spring-security listener

37
推荐指数
5
解决办法
4万
查看次数

允许OPTIONS HTTP方法执行oauth/token请求

我正在尝试为我的角应用程序启用oauth2令牌获取.我的配置工作正常(身份验证对所有请求都正常工作,令牌提取工作正常)但有一个问题.

CORS请求要求在GET之前将OPTIONS请求发送到服务器.更糟糕的是,该请求不包含任何身份验证标头.我希望此请求始终返回200状态,而无需在服务器上进行任何身份验证.可能吗?也许我错过了什么

我的春季安全配置:

@Configuration
@EnableWebSecurity
@EnableAuthorizationServer
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);

@Inject
private UserService userService;

@Bean
public TokenStore tokenStore() {
    return new InMemoryTokenStore();
}

@Bean
public DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(tokenStore());
    return defaultTokenServices;
}

@Bean
public WebResponseExceptionTranslator webResponseExceptionTranslator() {
    return new DefaultWebResponseExceptionTranslator() {

        @Override
        public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
            ResponseEntity<OAuth2Exception> responseEntity = super.translate(e);
            OAuth2Exception body = responseEntity.getBody();
            HttpHeaders headers = new HttpHeaders();
            headers.setAll(responseEntity.getHeaders().toSingleValueMap());
            headers.set("Access-Control-Allow-Origin", "*");
            headers.set("Access-Control-Allow-Methods", …
Run Code Online (Sandbox Code Playgroud)

spring oauth spring-security cors oauth-2.0

37
推荐指数
2
解决办法
4万
查看次数

如何使用OAuth2RestTemplate?

我试图了解如何使用OAuth2RestTemplate对象来使用我的OAuth2安全REST服务(在不同的项目下运行,让我们假设在不同的服务器等...)

我的休息服务是:

http://localhost:8082/app/helloworld
Run Code Online (Sandbox Code Playgroud)

- >访问此URL会生成错误,因为我未经过身份验证

要请求令牌,我会去:

http://localhost:8082/app/oauth/token?grant_type=password&client_id=restapp&client_secret=restapp&username=**USERNAME**&password=**PASSWORD**
Run Code Online (Sandbox Code Playgroud)

收到令牌后,我可以使用以下URL连接到REST API(插入示例令牌)

http://localhost:8082/app/helloworld/?access_token=**4855f557-c6ee-43b7-8617-c24591965206**
Run Code Online (Sandbox Code Playgroud)

现在我的问题是如何实现可以使用这个OAuth2安全REST API的第二个应用程序?我真的没有找到任何提供用户名和密码的工作示例(例如来自登录表单),然后生成一个令牌,可以重新使用该令牌从REST API获取数据.

我目前尝试使用以下对象:

BaseOAuth2ProtectedResourceDetails baseOAuth2ProtectedResourceDetails =  new BaseOAuth2ProtectedResourceDetails();
baseOAuth2ProtectedResourceDetails.setClientId("restapp");
baseOAuth2ProtectedResourceDetails.setClientSecret("restapp");
baseOAuth2ProtectedResourceDetails.setGrantType("password");
// how to set user name and password ???

DefaultAccessTokenRequest accessTokenRequest = new DefaultAccessTokenRequest();
OAuth2ClientContext oAuth2ClientContext = new DefaultOAuth2ClientContext(accessTokenRequest());

OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(baseOAuth2ProtectedResourceDetails,oAuth2ClientContext);
Run Code Online (Sandbox Code Playgroud)

但这只是不起作用:(

非常感谢任何想法或非常感谢链接到工作示例和教程.

api rest spring oauth spring-security

37
推荐指数
2
解决办法
9万
查看次数

使用JWT和Basic身份验证保护REST应用程序是否有意义?

我有一个Spring REST应用程序,它首先使用基本身份验证进行保护.

然后我添加了一个登录控制器,它创建了一个JWT JSON Web令牌,用于后续请求.

我可以将以下代码移出登录控制器并进入安全过滤器吗?然后我不再需要登录控制器了.

tokenAuthenticationService.addTokenToResponseHeader(responseHeaders, credentialsResource.getEmail());
Run Code Online (Sandbox Code Playgroud)

或者我可以删除基本身份验证吗?

将基本身份验证与JWT混合是一种好的设计吗?

虽然一切正常,但我在这里有点黑暗,以便最好地设计这种安全性.

spring-security basic-authentication jwt

37
推荐指数
1
解决办法
2万
查看次数