问:
How to enable Bearer authentication on Spring Boot application?
What I am trying to achieve is:

users, authorities, clients and access tokens stored in a database (i.e. MySQL) accessed via jdbc

API exposes endpoints for you to ask "can I have an OAuth2 bearer token? I know the client ID and secret"

API lets you access MVC endpoints if you supply a Bearer token in your request header

I got pretty far with this — the first two points are working.

I was not able to use a completely default OAuth2 setup for my Spring Boot application, because the standard table names are already in-use in my database (I have a "users" table already, for example).

I constructed my own instances of JdbcTokenStore, JdbcClientDetailsService, and JdbcAuthorizationCodeServices manually, configured them to use the custom table names from my database, and set up my application to use these instances.

So, here's what I have so far. I can ask for a Bearer token:

# The `-u` switch provides the client ID & secret over HTTP Basic Auth
curl -u8fc9d384-619a-11e7-9fe6-246798c61721:9397ce6c-619a-11e7-9fe6-246798c61721 \
'http://localhost:8080/oauth/token' \
-d grant_type=password \
-d username=bob \
-d password=tom
```

<p>I receive a response; nice!</p>

<pre class="lang-json prettyprint-override"><code>{"access_token":"1ee9b381-e71a-4e2f-8782-54ab1ce4d140","token_type":"bearer","refresh_token":"8db897c7-03c6-4fc3-bf13-8b0296b41776","expires_in":26321,"scope":"read write"}
</code>```

Now I try to use that token:

curl 'http://localhost:8080/test' \
-H "Authorization: Bearer 1ee9b381-e71a-4e2f-8782-54ab1ce4d140"
```

<p>Alas:</p>

<pre class="lang-json prettyprint-override"><code>{
   "timestamp":1499452163373,
   "status":401,
   "error":"Unauthorized",
   "message":"Full authentication is required to access this resource",
   "path":"/test"
}
</code>```

This means (in this particular case) that it has fallen back to anonymous authentication. You can see the real error if I add .anonymous().disable() to my HttpSecurity:

{
   "timestamp":1499452555312,
   "status":401,
   "error":"Unauthorized",
   "message":"An Authentication object was not found in the SecurityContext",
   "path":"/test"
}
```

<hr>

<p>I investigated this more deeply by increasing the logging verbosity:</p>

<pre class="lang-yaml prettyprint-override"><code>logging.level:
    org.springframework:
      security: DEBUG
</code>```

This reveals the 10 filters through which my request travels:

```<code>o.s.security.web.FilterChainProxy        : /test at position 1 of 10 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.security.web.FilterChainProxy        : /test at position 2 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
o.s.security.web.FilterChainProxy        : /test at position 3 of 10 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.security.web.FilterChainProxy        : /test at position 4 of 10 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.security.web.FilterChainProxy        : /test at position 5 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
o.s.security.web.FilterChainProxy        : /test at position 6 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.security.web.FilterChainProxy        : /test at position 7 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.security.web.FilterChainProxy        : /test at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.security.web.FilterChainProxy        : /test at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.security.web.FilterChainProxy        : /test at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /test; Attributes: [authenticated]
o.s.s.w.a.ExceptionTranslationFilter     : Authentication exception occurred; redirecting to authentication entry point

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
</code>```

That's what it looks like if Anonymous users are disabled. If they're enabled: AnonymousAuthenticationFilter is added into the filter chain just after SecurityContextHolderAwareRequestFilter, and the sequence ends more like this:

```<code>o.s.security.web.FilterChainProxy        : /test at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /test; Attributes: [authenticated]
o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@5ff24abf, returned: -1
o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]
</code>```

Either way: no good.

Essentially it indicates to me that we are missing some step in the filter chain. We need a filter that would read the header of the ServletRequest, then populate the security context's authentication:

SecurityContextHolder.getContext().setAuthentication(request: HttpServletRequest);
```

<p>I wonder how to get such a filter?</p>

<hr>

<p>This is what my application looks like. It's Kotlin, but hopefully it should make sense to the Java eye.</p>

<p><strong>Application.kt:</strong></p>

<pre class="lang-kotlin prettyprint-override"><code>@SpringBootApplication(scanBasePackageClasses=arrayOf(
        com.example.domain.Package::class,
        com.example.service.Package::class,
        com.example.web.Package::class
))
class MyApplication

fun main(args: Array<String>) {
    SpringApplication.run(MyApplication::class.java, *args)
}
</code>```

TestController:

@RestController
class TestController {
    @RequestMapping("/test")
    fun Test(): String {
        return "hey there"
    }
}
```

<p><strong>MyWebSecurityConfigurerAdapter:</strong></p>

<pre class="lang-kotlin prettyprint-override"><code>@Configuration
@EnableWebSecurity
/**
 * Based on:
 * https://stackoverflow.com/questions/25383286/spring-security-custom-userdetailsservice-and-custom-user-class
 *
 * Password encoder:
 * http://www.baeldung.com/spring-security-authentication-with-a-database
 */
class MyWebSecurityConfigurerAdapter(
        val userDetailsService: MyUserDetailsService
) : WebSecurityConfigurerAdapter() {

    private val passwordEncoder = BCryptPasswordEncoder()

    override fun userDetailsService() : UserDetailsService {
        return userDetailsService
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth
                .authenticationProvider(authenticationProvider())
    }

    @Bean
    fun authenticationProvider() : AuthenticationProvider {
        val authProvider = DaoAuthenticationProvider()
        authProvider.setUserDetailsService(userDetailsService())
        authProvider.setPasswordEncoder(passwordEncoder)
        return authProvider
    }

    override fun configure(http: HttpSecurity?) {
        http!!
                .anonymous().disable()
                .authenticationProvider(authenticationProvider())
                .authorizeRequests()
                    .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable()
    }
}
</code>```

MyAuthorizationServerConfigurerAdapter:

/**
 * Based on:
 * https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/jdbc/src/main/java/demo/Application.java#L68
 */
@Configuration
@EnableAuthorizationServer
class MyAuthorizationServerConfigurerAdapter(
        val auth : AuthenticationManager,
        val dataSource: DataSource,
        val userDetailsService: UserDetailsService

) : AuthorizationServerConfigurerAdapter() {

    private val passwordEncoder = BCryptPasswordEncoder()

    @Bean
    fun tokenStore(): JdbcTokenStore {
        val tokenStore = JdbcTokenStore(dataSource)
        val oauthAccessTokenTable = "auth_schema.oauth_access_token"
        val oauthRefreshTokenTable = "auth_schema.oauth_refresh_token"
        tokenStore.setDeleteAccessTokenFromRefreshTokenSql("delete from ${oauthAccessTokenTable} where refresh_token = ?")
        tokenStore.setDeleteAccessTokenSql("delete from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setDeleteRefreshTokenSql("delete from ${oauthRefreshTokenTable} where token_id = ?")
        tokenStore.setInsertAccessTokenSql("insert into ${oauthAccessTokenTable} (token_id, token, authentication_id, " +
                "user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)")
        tokenStore.setInsertRefreshTokenSql("insert into ${oauthRefreshTokenTable} (token_id, token, authentication) values (?, ?, ?)")
        tokenStore.setSelectAccessTokenAuthenticationSql("select token_id, authentication from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setSelectAccessTokenFromAuthenticationSql("select token_id, token from ${oauthAccessTokenTable} where authentication_id = ?")
        tokenStore.setSelectAccessTokenSql("select token_id, token from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setSelectAccessTokensFromClientIdSql("select token_id, token from ${oauthAccessTokenTable} where client_id = ?")
        tokenStore.setSelectAccessTokensFromUserNameAndClientIdSql("select token_id, token from ${oauthAccessTokenTable} where user_name = ? and client_id = ?")
        tokenStore.setSelectAccessTokensFromUserNameSql("select token_id, token from ${oauthAccessTokenTable} where user_name = ?")
        tokenStore.setSelectRefreshTokenAuthenticationSql("select token_id, authentication from ${oauthRefreshTokenTable} where token_id = ?")
        tokenStore.setSelectRefreshTokenSql("select token_id, token from ${oauthRefreshTokenTable} where token_id = ?")
        return tokenStore
    }

    override fun configure(security: AuthorizationServerSecurityConfigurer?) {
        security!!.passwordEncoder(passwordEncoder)
    }

    override fun configure(clients: ClientDetailsServiceConfigurer?) {
        val clientDetailsService = JdbcClientDetailsService(dataSource)
        clientDetailsService.setPasswordEncoder(passwordEncoder)

        val clientDetailsTable = "auth_schema.oauth_client_details"
        val CLIENT_FIELDS_FOR_UPDATE = "resource_ids, scope, " +
                "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " +
                "refresh_token_validity, additional_information, autoapprove"
        val CLIENT_FIELDS = "client_secret, ${CLIENT_FIELDS_FOR_UPDATE}"
        val BASE_FIND_STATEMENT = "select client_id, ${CLIENT_FIELDS} from ${clientDetailsTable}"

        clientDetailsService.setFindClientDetailsSql("${BASE_FIND_STATEMENT} order by client_id")
        clientDetailsService.setDeleteClientDetailsSql("delete from ${clientDetailsTable} where client_id = ?")
        clientDetailsService.setInsertClientDetailsSql("insert into ${clientDetailsTable} (${CLIENT_FIELDS}," +
                " client_id) values (?,?,?,?,?,?,?,?,?,?,?)")
        clientDetailsService.setSelectClientDetailsSql("${BASE_FIND_STATEMENT} where client_id = ?")
        clientDetailsService.setUpdateClientDetailsSql("update ${clientDetailsTable} set " +
                "${CLIENT_FIELDS_FOR_UPDATE.replace(", ", "=?, ")}=? where client_id = ?")
        clientDetailsService.setUpdateClientSecretSql("update ${clientDetailsTable} set client_secret = ? where client_id = ?")
        clients!!.withClientDetails(clientDetailsService)
    }

    override fun configure(endpoints: AuthorizationServerEndpointsConfigurer?) {
        endpoints!!
                .authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(auth)
                .tokenStore(tokenStore())
                .approvalStoreDisabled()
                .userDetailsService(userDetailsService)
    }

    @Bean
    protected fun authorizationCodeServices() : AuthorizationCodeServices {
        val codeServices = JdbcAuthorizationCodeServices(dataSource)
        val oauthCodeTable = "auth_schema.oauth_code"
        codeServices.setSelectAuthenticationSql("select code, authentication from ${oauthCodeTable} where code = ?")
        codeServices.setInsertAuthenticationSql("insert into ${oauthCodeTable} (code, authentication) values (?, ?)")
        codeServices.setDeleteAuthenticationSql("delete from ${oauthCodeTable} where code = ?")
        return codeServices
    }
}
```

<p><strong>MyAuthorizationServerConfigurerAdapter:</strong></p>

<pre class="lang-kotlin prettyprint-override"><code>@Service
class MyUserDetailsService(
        val theDataSource: DataSource
) : JdbcUserDetailsManager() {
    @PostConstruct
    fun init() {
        dataSource = theDataSource

        val usersTable = "auth_schema.users"
        val authoritiesTable = "auth_schema.authorities"

        setChangePasswordSql("update ${usersTable} set password = ? where username = ?")
        setCreateAuthoritySql("insert into ${authoritiesTable} (username, authority) values (?,?)")
        setCreateUserSql("insert into ${usersTable} (username, password, enabled) values (?,?,?)")
        setDeleteUserAuthoritiesSql("delete from ${authoritiesTable} where username = ?")
        setDeleteUserSql("delete from ${usersTable} where username = ?")
        setUpdateUserSql("update ${usersTable} set password = ?, enabled = ? where username = ?")
        setUserExistsSql("select username from ${usersTable} where username = ?")

        setAuthoritiesByUsernameQuery("select username,authority from ${authoritiesTable} where username = ?")
        setUsersByUsernameQuery("select username,password,enabled from ${usersTable} " + "where username = ?")
    }
}
</code>```

Any ideas? Could it be that I need to somehow install the OAuth2AuthenticationProcessingFilter into my filter chain?

I do get such messages on startup… could these be related to the problem?

```<code>u.c.c.h.s.auth.MyUserDetailsService      : No authentication manager set. Reauthentication of users when changing passwords will not be performed.
s.c.a.w.c.WebSecurityConfigurerAdapter$3 : No authenticationProviders and no parentAuthenticationManager defined. Returning null.
</code>```

EDIT:

It looks like installing OAuth2AuthenticationProcessingFilter is the job of a ResourceServerConfigurerAdapter. I have added the following class:

MyResourceServerConfigurerAdapter:

@Configuration
@EnableResourceServer
class MyResourceServerConfigurerAdapter : ResourceServerConfigurerAdapter()
```

And I confirm in the debugger that this causes ResourceServerSecurityConfigurer to enter its configure(http: HttpSecurity) method, which does look like it tries to install a OAuth2AuthenticationProcessingFilter into the filter chain.

But it doesn't look like it succeeded. According to Spring Security's debug output: I still have the same number of filters in my filter chain. OAuth2AuthenticationProcessingFilter is not in there. What's going on?

EDIT2: I wonder if the problem is that I have two classes (WebSecurityConfigurerAdapter, ResourceServerConfigurerAdapter) trying to configure HttpSecurity. Is it mutually exclusive?

答:
Yes! The problem was related to the fact that I had registered both a WebSecurityConfigurerAdapter and a ResourceServerConfigurerAdapter.

Solution: delete the WebSecurityConfigurerAdapter. And use this ResourceServerConfigurerAdapter:

@Configuration
@EnableResourceServer
class MyResourceServerConfigurerAdapter(
        val userDetailsService: MyUserDetailsService
) : ResourceServerConfigurerAdapter() {
    private val passwordEncoder = BCryptPasswordEncoder()

    override fun configure(http: HttpSecurity?) {
        http!!
                .authenticationProvider(authenticationProvider())
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable()
    }

    @Bean
    fun authenticationProvider() : AuthenticationProvider {
        val authProvider = DaoAuthenticationProvider()
        authProvider.setUserDetailsService(userDetailsService)
        authProvider.setPasswordEncoder(passwordEncoder)
        return authProvider
    }
}
```

EDIT: In order to get Bearer auth to apply to all endpoints (for example the /metrics endpoint installed by Spring Actuator), I found that I had to also add security.oauth2.resource.filter-order: 3 to my application.yml. See this answer.

Body:
What I am trying to achieve is:

users, authorities, clients and access tokens stored in a database (i.e. MySQL) accessed via jdbc

API exposes endpoints for you to ask "can I have an OAuth2 bearer token? I know the client ID and secret"

API lets you access MVC endpoints if you supply a Bearer token in your request header

I got pretty far with this — the first two points are working.

I was not able to use a completely default OAuth2 setup for my Spring Boot application, because the standard table names are already in-use in my database (I have a "users" table already, for example).

I constructed my own instances of JdbcTokenStore, JdbcClientDetailsService, and JdbcAuthorizationCodeServices manually, configured them to use the custom table names from my database, and set up my application to use these instances.

So, here's what I have so far. I can ask for a Bearer token:

# The `-u` switch provides the client ID & secret over HTTP Basic Auth
curl -u8fc9d384-619a-11e7-9fe6-246798c61721:9397ce6c-619a-11e7-9fe6-246798c61721 \
'http://localhost:8080/oauth/token' \
-d grant_type=password \
-d username=bob \
-d password=tom

I receive a response; nice!

{"access_token":"1ee9b381-e71a-4e2f-8782-54ab1ce4d140","token_type":"bearer","refresh_token":"8db897c7-03c6-4fc3-bf13-8b0296b41776","expires_in":26321,"scope":"read write"}

Now I try to use that token:

curl 'http://localhost:8080/test' \
-H "Authorization: Bearer 1ee9b381-e71a-4e2f-8782-54ab1ce4d140"

Alas:

{
   "timestamp":1499452163373,
   "status":401,
   "error":"Unauthorized",
   "message":"Full authentication is required to access this resource",
   "path":"/test"
}

This means (in this particular case) that it has fallen back to anonymous authentication. You can see the real error if I add .anonymous().disable() to my HttpSecurity:

{
   "timestamp":1499452555312,
   "status":401,
   "error":"Unauthorized",
   "message":"An Authentication object was not found in the SecurityContext",
   "path":"/test"
}

I investigated this more deeply by increasing the logging verbosity:

logging.level:
    org.springframework:
      security: DEBUG

This reveals the 10 filters through which my request travels:

o.s.security.web.FilterChainProxy        : /test at position 1 of 10 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.security.web.FilterChainProxy        : /test at position 2 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
o.s.security.web.FilterChainProxy        : /test at position 3 of 10 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.security.web.FilterChainProxy        : /test at position 4 of 10 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.security.web.FilterChainProxy        : /test at position 5 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
o.s.security.web.FilterChainProxy        : /test at position 6 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.security.web.FilterChainProxy        : /test at position 7 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.security.web.FilterChainProxy        : /test at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.security.web.FilterChainProxy        : /test at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.security.web.FilterChainProxy        : /test at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /test; Attributes: [authenticated]
o.s.s.w.a.ExceptionTranslationFilter     : Authentication exception occurred; redirecting to authentication entry point

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:379) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]

That's what it looks like if Anonymous users are disabled. If they're enabled: AnonymousAuthenticationFilter is added into the filter chain just after SecurityContextHolderAwareRequestFilter, and the sequence ends more like this:

o.s.security.web.FilterChainProxy        : /test at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /test; Attributes: [authenticated]
o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@5ff24abf, returned: -1
o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.3.RELEASE.jar:4.2.3.RELEASE]

Either way: no good.

Essentially it indicates to me that we are missing some step in the filter chain. We need a filter that would read the header of the ServletRequest, then populate the security context's authentication:

SecurityContextHolder.getContext().setAuthentication(request: HttpServletRequest);

I wonder how to get such a filter?

This is what my application looks like. It's Kotlin, but hopefully it should make sense to the Java eye.

Application.kt:

@SpringBootApplication(scanBasePackageClasses=arrayOf(
        com.example.domain.Package::class,
        com.example.service.Package::class,
        com.example.web.Package::class
))
class MyApplication

fun main(args: Array<String>) {
    SpringApplication.run(MyApplication::class.java, *args)
}

TestController:

@RestController
class TestController {
    @RequestMapping("/test")
    fun Test(): String {
        return "hey there"
    }
}

MyWebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
/**
 * Based on:
 * https://stackoverflow.com/questions/25383286/spring-security-custom-userdetailsservice-and-custom-user-class
 *
 * Password encoder:
 * http://www.baeldung.com/spring-security-authentication-with-a-database
 */
class MyWebSecurityConfigurerAdapter(
        val userDetailsService: MyUserDetailsService
) : WebSecurityConfigurerAdapter() {

    private val passwordEncoder = BCryptPasswordEncoder()

    override fun userDetailsService() : UserDetailsService {
        return userDetailsService
    }

    override fun configure(auth: AuthenticationManagerBuilder) {
        auth
                .authenticationProvider(authenticationProvider())
    }

    @Bean
    fun authenticationProvider() : AuthenticationProvider {
        val authProvider = DaoAuthenticationProvider()
        authProvider.setUserDetailsService(userDetailsService())
        authProvider.setPasswordEncoder(passwordEncoder)
        return authProvider
    }

    override fun configure(http: HttpSecurity?) {
        http!!
                .anonymous().disable()
                .authenticationProvider(authenticationProvider())
                .authorizeRequests()
                    .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable()
    }
}

MyAuthorizationServerConfigurerAdapter:

/**
 * Based on:
 * https://github.com/spring-projects/spring-security-oauth/blob/master/tests/annotation/jdbc/src/main/java/demo/Application.java#L68
 */
@Configuration
@EnableAuthorizationServer
class MyAuthorizationServerConfigurerAdapter(
        val auth : AuthenticationManager,
        val dataSource: DataSource,
        val userDetailsService: UserDetailsService

) : AuthorizationServerConfigurerAdapter() {

    private val passwordEncoder = BCryptPasswordEncoder()

    @Bean
    fun tokenStore(): JdbcTokenStore {
        val tokenStore = JdbcTokenStore(dataSource)
        val oauthAccessTokenTable = "auth_schema.oauth_access_token"
        val oauthRefreshTokenTable = "auth_schema.oauth_refresh_token"
        tokenStore.setDeleteAccessTokenFromRefreshTokenSql("delete from ${oauthAccessTokenTable} where refresh_token = ?")
        tokenStore.setDeleteAccessTokenSql("delete from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setDeleteRefreshTokenSql("delete from ${oauthRefreshTokenTable} where token_id = ?")
        tokenStore.setInsertAccessTokenSql("insert into ${oauthAccessTokenTable} (token_id, token, authentication_id, " +
                "user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)")
        tokenStore.setInsertRefreshTokenSql("insert into ${oauthRefreshTokenTable} (token_id, token, authentication) values (?, ?, ?)")
        tokenStore.setSelectAccessTokenAuthenticationSql("select token_id, authentication from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setSelectAccessTokenFromAuthenticationSql("select token_id, token from ${oauthAccessTokenTable} where authentication_id = ?")
        tokenStore.setSelectAccessTokenSql("select token_id, token from ${oauthAccessTokenTable} where token_id = ?")
        tokenStore.setSelectAccessTokensFromClientIdSql("select token_id, token from ${oauthAccessTokenTable} where client_id = ?")
        tokenStore.setSelectAccessTokensFromUserNameAndClientIdSql("select token_id, token from ${oauthAccessTokenTable} where user_name = ? and client_id = ?")
        tokenStore.setSelectAccessTokensFromUserNameSql("select token_id, token from ${oauthAccessTokenTable} where user_name = ?")
        tokenStore.setSelectRefreshTokenAuthenticationSql("select token_id, authentication from ${oauthRefreshTokenTable} where token_id = ?")
        tokenStore.setSelectRefreshTokenSql("select token_id, token from ${oauthRefreshTokenTable} where token_id = ?")
        return tokenStore
    }

    override fun configure(security: AuthorizationServerSecurityConfigurer?) {
        security!!.passwordEncoder(passwordEncoder)
    }

    override fun configure(clients: ClientDetailsServiceConfigurer?) {
        val clientDetailsService = JdbcClientDetailsService(dataSource)
        clientDetailsService.setPasswordEncoder(passwordEncoder)

        val clientDetailsTable = "auth_schema.oauth_client_details"
        val CLIENT_FIELDS_FOR_UPDATE = "resource_ids, scope, " +
                "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, " +
                "refresh_token_validity, additional_information, autoapprove"
        val CLIENT_FIELDS = "client_secret, ${CLIENT_FIELDS_FOR_UPDATE}"
        val BASE_FIND_STATEMENT = "select client_id, ${CLIENT_FIELDS} from ${clientDetailsTable}"

        clientDetailsService.setFindClientDetailsSql("${BASE_FIND_STATEMENT} order by client_id")
        clientDetailsService.setDeleteClientDetailsSql("delete from ${clientDetailsTable} where client_id = ?")
        clientDetailsService.setInsertClientDetailsSql("insert into ${clientDetailsTable} (${CLIENT_FIELDS}," +
                " client_id) values (?,?,?,?,?,?,?,?,?,?,?)")
        clientDetailsService.setSelectClientDetailsSql("${BASE_FIND_STATEMENT} where client_id = ?")
        clientDetailsService.setUpdateClientDetailsSql("update ${clientDetailsTable} set " +
                "${CLIENT_FIELDS_FOR_UPDATE.replace(", ", "=?, ")}=? where client_id = ?")
        clientDetailsService.setUpdateClientSecretSql("update ${clientDetailsTable} set client_secret = ? where client_id = ?")
        clients!!.withClientDetails(clientDetailsService)
    }

    override fun configure(endpoints: AuthorizationServerEndpointsConfigurer?) {
        endpoints!!
                .authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(auth)
                .tokenStore(tokenStore())
                .approvalStoreDisabled()
                .userDetailsService(userDetailsService)
    }

    @Bean
    protected fun authorizationCodeServices() : AuthorizationCodeServices {
        val codeServices = JdbcAuthorizationCodeServices(dataSource)
        val oauthCodeTable = "auth_schema.oauth_code"
        codeServices.setSelectAuthenticationSql("select code, authentication from ${oauthCodeTable} where code = ?")
        codeServices.setInsertAuthenticationSql("insert into ${oauthCodeTable} (code, authentication) values (?, ?)")
        codeServices.setDeleteAuthenticationSql("delete from ${oauthCodeTable} where code = ?")
        return codeServices
    }
}

MyAuthorizationServerConfigurerAdapter:

@Service
class MyUserDetailsService(
        val theDataSource: DataSource
) : JdbcUserDetailsManager() {
    @PostConstruct
    fun init() {
        dataSource = theDataSource

        val usersTable = "auth_schema.users"
        val authoritiesTable = "auth_schema.authorities"

        setChangePasswordSql("update ${usersTable} set password = ? where username = ?")
        setCreateAuthoritySql("insert into ${authoritiesTable} (username, authority) values (?,?)")
        setCreateUserSql("insert into ${usersTable} (username, password, enabled) values (?,?,?)")
        setDeleteUserAuthoritiesSql("delete from ${authoritiesTable} where username = ?")
        setDeleteUserSql("delete from ${usersTable} where username = ?")
        setUpdateUserSql("update ${usersTable} set password = ?, enabled = ? where username = ?")
        setUserExistsSql("select username from ${usersTable} where username = ?")

        setAuthoritiesByUsernameQuery("select username,authority from ${authoritiesTable} where username = ?")
        setUsersByUsernameQuery("select username,password,enabled from ${usersTable} " + "where username = ?")
    }
}

Any ideas? Could it be that I need to somehow install the OAuth2AuthenticationProcessingFilter into my filter chain?

I do get such messages on startup… could these be related to the problem?

u.c.c.h.s.auth.MyUserDetailsService      : No authentication manager set. Reauthentication of users when changing passwords will not be performed.
s.c.a.w.c.WebSecurityConfigurerAdapter$3 : No authenticationProviders and no parentAuthenticationManager defined. Returning null.

EDIT:

It looks like installing OAuth2AuthenticationProcessingFilter is the job of a ResourceServerConfigurerAdapter. I have added the following class:

MyResourceServerConfigurerAdapter:

@Configuration
@EnableResourceServer
class MyResourceServerConfigurerAdapter : ResourceServerConfigurerAdapter()

And I confirm in the debugger that this causes ResourceServerSecurityConfigurer to enter its configure(http: HttpSecurity) method, which does look like it tries to install a OAuth2AuthenticationProcessingFilter into the filter chain.

But it doesn't look like it succeeded. According to Spring Security's debug output: I still have the same number of filters in my filter chain. OAuth2AuthenticationProcessingFilter is not in there. What's going on?

EDIT2: I wonder if the problem is that I have two classes (WebSecurityConfigurerAdapter, ResourceServerConfigurerAdapter) trying to configure HttpSecurity. Is it mutually exclusive?

Body:
Yes! The problem was related to the fact that I had registered both a WebSecurityConfigurerAdapter and a ResourceServerConfigurerAdapter.

Solution: delete the WebSecurityConfigurerAdapter. And use this ResourceServerConfigurerAdapter:

@Configuration
@EnableResourceServer
class MyResourceServerConfigurerAdapter(
        val userDetailsService: MyUserDetailsService
) : ResourceServerConfigurerAdapter() {
    private val passwordEncoder = BCryptPasswordEncoder()

    override fun configure(http: HttpSecurity?) {
        http!!
                .authenticationProvider(authenticationProvider())
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and()
                .csrf().disable()
    }

    @Bean
    fun authenticationProvider() : AuthenticationProvider {
        val authProvider = DaoAuthenticationProvider()
        authProvider.setUserDetailsService(userDetailsService)
        authProvider.setPasswordEncoder(passwordEncoder)
        return authProvider
    }
}

EDIT: In order to get Bearer auth to apply to all endpoints (for example the /metrics endpoint installed by Spring Actuator), I found that I had to also add security.oauth2.resource.filter-order: 3 to my application.yml. See this answer.


来源: stackexchange

问:
Most repeating character in a string
We are given a string , for example, take "TUOPPPPJHHTT"
We wish to find out which character occurs the most number of times CONTINUOUSLY in the string and how many times.
In this case, its P occurring 4 times.

I tried running a for loop as following

```<code>char[] array = S.toCharArray();
int count=1;
for(int i =1; i < S.length(); i++) {
    if(array[i] == array[i-1]) {
        count++;
    }
}
</code>```

but in this approach, the problem is it will count repeated occurrences of all alphabets.

答:
You could try this code:</p>

```<code>import java.util.Scanner;

public class HighestOccuringConsecutiveChar
{

    public static char highestOccuringConsecutiveCharacter(String a)
    {
        int c= 0, cNext = 0;
        char ans = '\0';
        for(int i = 0; i < a.length()-1; i++)
        {
            if(a.charAt(i) == a.charAt(i+1))
                cNext++;

            if(cNext > c)
            {
                ans = a.charAt(i);
                c = cNext;
            }
            if(a.charAt(i) != a.charAt(i))
                cNext = 0;
        if(c == 0 && cNext == 0)
            ans = a.charAt(i);
        }
        return ans;
    }

    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        String str = new String();
        str = s.nextLine();
        System.out.println(highestOccuringConsecutiveCharacter(str));
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Most repeating character in a string

Body:
We are given a string , for example, take "TUOPPPPJHHTT"
We wish to find out which character occurs the most number of times CONTINUOUSLY in the string and how many times.
In this case, its P occurring 4 times.

I tried running a for loop as following

char[] array = S.toCharArray();
int count=1;
for(int i =1; i < S.length(); i++) {
    if(array[i] == array[i-1]) {
        count++;
    }
}

but in this approach, the problem is it will count repeated occurrences of all alphabets.

Body:
You could try this code:

import java.util.Scanner;

public class HighestOccuringConsecutiveChar
{

    public static char highestOccuringConsecutiveCharacter(String a)
    {
        int c= 0, cNext = 0;
        char ans = '\0';
        for(int i = 0; i < a.length()-1; i++)
        {
            if(a.charAt(i) == a.charAt(i+1))
                cNext++;

            if(cNext > c)
            {
                ans = a.charAt(i);
                c = cNext;
            }
            if(a.charAt(i) != a.charAt(i))
                cNext = 0;
        if(c == 0 && cNext == 0)
            ans = a.charAt(i);
        }
        return ans;
    }

    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        String str = new String();
        str = s.nextLine();
        System.out.println(highestOccuringConsecutiveCharacter(str));
    }
}


问:
Error while connecting to external SQL Server with an IP using SQL Management Studio 2005
Error while connecting to external SQL Server IP using SQL Management Studio 2005 address

TITLE: Connect to Server

Cannot connect to 1.2.3.4\SQLEXPRESS.

ADDITIONAL INFORMATION:

A network-related or instance-specific error occurred while
  establishing a connection to SQL
  Server. The server was not found or
  was not accessible. Verify that the
  instance name is correct and that SQL
  Server is configured to allow remote
  connections. (provider: SQL Network
  Interfaces, error: 26 - Error Locating
  Server/Instance Specified) (Microsoft
  SQL Server, Error: -1)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1&LinkId=20476

答:
By default, SQL Server 2005 doesn’t allow remote connection so you have to enable it manually. So if @abatishchev's solution doesn't get you going; it may be you haven't set the permissions to connect.

Run the Surface Area Configuration Manager (it should be in the SQL Server folder in My Programs under Configuration Tools).
Choose Surface Area Configuration for Services and Connections
Select your server expand database engine and then remote connections and enable TCP/IP and / or tcp/ip and named pipes. Click Apply.

Whilst you are here check the SQL Server Browser is set to run. Expand it out and choose the service; change the startup type to be Automatic.

Try again in management studio express to connect to the machine.

ContentLicense: CC BY-SA 2.5


问:
Execute JavaScript in a modal window
I have the following JS code:

```<code><script type="text/javascript">
    $(document).ready(function () {
        var items = "<option value='0'>Select</option>";
        $('#DistrictID').html(items);
    });
</script>
</code>```

This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.

But since it is mark as

```<code>$(document).ready
</code>```

This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?

Thanks in advance!

Regards,

答:
Try something like this:</p>
```<code>$('#idofselectelement').change(function() {
    //grab the selected option and then do what you want with it.
});
</code>```

Title: Execute JavaScript in a modal window

Body:
I have the following JS code:

This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.

But since it is mark as

$(document).ready

This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?

Thanks in advance!

Regards,

Body:
Try something like this:

$('#idofselectelement').change(function() {
    //grab the selected option and then do what you want with it.
});

ContentLicense: CC BY-SA 4.0


问:
How to assign a method to a button when pressed or released with ActionListener in Java?
I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.

This is what I have for a regular button pressing.

```<code> leftButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Pressed");
        }
    });
</code>```

I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.

答:
Use custom class and use it</p>

```<code> leftButton.getModel().addChangeListener(new BtnCusttomListener());

 private class BtnCusttomListener implements ChangeListener {
        private boolean pressed = false;  // holds the last pressed state of the button

        @Override
        public void stateChanged(ChangeEvent e) {
            ButtonModel Buttonmodel = (ButtonModel) e.getSource();

            // if the current state differs from the previous state
            if (model.isPressed() != pressed) {
                String text = "Button pressed: " + model.isPressed() + "\n";
                textArea.append(text);
                pressed = model.isPressed();
            }
        }
    }
</code>```

Body:
I am new to coding GUIs in Java and I am trying to just print a message on the terminal when a button is pressed and another one when it is released.

This is what I have for a regular button pressing.

 leftButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Pressed");
        }
    });

I did this with the help of IntelliJ IDEA. I want to make the button send a message when pressed and a different thing when released.

Body:
Use custom class and use it

 leftButton.getModel().addChangeListener(new BtnCusttomListener());

 private class BtnCusttomListener implements ChangeListener {
        private boolean pressed = false;  // holds the last pressed state of the button

        @Override
        public void stateChanged(ChangeEvent e) {
            ButtonModel Buttonmodel = (ButtonModel) e.getSource();

            // if the current state differs from the previous state
            if (model.isPressed() != pressed) {
                String text = "Button pressed: " + model.isPressed() + "\n";
                textArea.append(text);
                pressed = model.isPressed();
            }
        }
    }


问:
flutter remove back button on appbar
I am wondering, if anyone knows of a way to remove the back button that shows up on the appBar in a flutter app when you use Navigator.pushNamed to go to another page. The reason I do not want it on this resulting page is that it is coming from the navigation and I want users to use the logout button instead, so that the session starts over.

答:
You can remove the back button by passing an empty new Container() as the leading argument to your AppBar.

If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed, try calling Navigator.pushReplacementNamed to cause the earlier route to disappear.

The function pushReplacementNamed will remove the previous route in the  backstack and replace it with the new route.

Full code sample for the latter is below.

```<code>import 'package:flutter/material.dart';

class LogoutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Logout Page"),
      ),
      body: new Center(
        child: new Text('You have been logged out'),
      ),
    );
  }

}
class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Remove Back Button"),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.fullscreen_exit),
        onPressed: () {
          Navigator.pushReplacementNamed(context, "/logout");
        },
      ),
    );
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      routes: {
        "/logout": (_) => new LogoutPage(),
      },
    );
  }
}
</code>```

Title: flutter remove back button on appbar

Body:
You can remove the back button by passing an empty new Container() as the leading argument to your AppBar.

If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling pushNamed, try calling Navigator.pushReplacementNamed to cause the earlier route to disappear.

The function pushReplacementNamed will remove the previous route in the  backstack and replace it with the new route.

Full code sample for the latter is below.

import 'package:flutter/material.dart';

class LogoutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Logout Page"),
      ),
      body: new Center(
        child: new Text('You have been logged out'),
      ),
    );
  }

}
class MyHomePage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Remove Back Button"),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.fullscreen_exit),
        onPressed: () {
          Navigator.pushReplacementNamed(context, "/logout");
        },
      ),
    );
  }
}

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
      routes: {
        "/logout": (_) => new LogoutPage(),
      },
    );
  }
}


问:
How to save image
I want to save image with userdefaults and use it in another view with this code but it shows an error .

```<code>UserDefaults.standard.set(img , forKey : "simg")
</code>```

please help me

答:
As others have said, don't save images to user defaults. It's only intended for small bits of data.

If all you want to do is to pass an image in another view controller, and you don't care about making the image persist if the user quits and re-launches the app, just pass the image in prepareForSegue.

Title: How to save image

Body:
I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : "simg")

please help me


问:
Why are my actionErrors and fieldErrors displayed with braces []?
Once the pages have captured errors within my Struts 2 application the errors are displayed correctly from my resource bundles however they are always displayed with a braces [].

For example:

```<code>[first name must not be empty]
</code>```

These are displayed through the tags:

```<code><s:actionerror />

<s:iterator value="fieldErrors">
   <s:property value="value" />
</s:iterator>
</code>```

These come through the Action-validation.xml and setting a addFieldError() through the validation method

Is this something to do with my theme being set to simple ? I can't see anything in documentation or anything through other posts.

答:
Why

No, it is not about theme. Take a look at getFieldErrors method. It returns map where value is a list of strings.

```<code>public Map<String, List<String>> getFieldErrors() {
    return validationAware.getFieldErrors();
}
</code>```

Your code iterates over map and value is a list. List as string will be displayed with surrounding braces.

How

If you need only value of the error message and not the key then you can use addActionError method instead and iterate over actionErrors.

If you want to iterate fieldErrors then you can do it like that.

```<code><s:iterator value="fieldErrors">
    <s:property value="key"/>:
    <s:iterator value="value">
        <s:property/>
    </s:iterator>
</s:iterator>
</code>```

And of course there are tags for displaying errors/messages, see Non-Form UI Tags.

Body:
Once the pages have captured errors within my Struts 2 application the errors are displayed correctly from my resource bundles however they are always displayed with a braces [].

For example:

[first name must not be empty]

These are displayed through the tags:

<s:actionerror />

<s:iterator value="fieldErrors">
   <s:property value="value" />
</s:iterator>

These come through the Action-validation.xml and setting a addFieldError() through the validation method

Is this something to do with my theme being set to simple ? I can't see anything in documentation or anything through other posts.

Body:
Why

No, it is not about theme. Take a look at getFieldErrors method. It returns map where value is a list of strings.

public Map<String, List<String>> getFieldErrors() {
    return validationAware.getFieldErrors();
}

Your code iterates over map and value is a list. List as string will be displayed with surrounding braces.

How

If you need only value of the error message and not the key then you can use addActionError method instead and iterate over actionErrors.

If you want to iterate fieldErrors then you can do it like that.

<s:iterator value="fieldErrors">
    <s:property value="key"/>:
    <s:iterator value="value">
        <s:property/>
    </s:iterator>
</s:iterator>

And of course there are tags for displaying errors/messages, see Non-Form UI Tags.


问:
Naive permutation algorithm that python generator function doesn't support
guys.
It seems like I don't really understand the concept of Python generator functions, because I haven't figured out mistake in this code that is supposed to produce all the permutations of the string characters.

For instance, this one is based on simple set expansion and it works

```<code>def permutations(seq):
    perm_set = set()

    def perm(cur_item_set, cur_str=''):
        if not cur_item_set:
            perm_set.add(cur_str)
        else:
            for item in cur_item_set:
                perm(cur_item_set - set(item), cur_str + item)

    perm(set(seq))

    for (i, item) in enumerate(perm_set):
        print(i + 1, item)

    permutations('abcdef')
</code>```

Meanwhile, this code doesn't work: list(g) provides []

```<code>def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            gen_perm(cur_item_set - {item}, cur_str + item)

g = gen_perm(set('abcd'))
</code>```

答:
When you recursively call gen_perm(), you don't do anything with the return value.

Try this, if yield from is available in your Python version (3.3 and above):

```<code>def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            yield from gen_perm(cur_item_set - {item}, cur_str + item)

g = gen_perm(set('abcd'))
print (list(g))
</code>```

Or this will work on all Python versions.

```<code>def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            for item2 in gen_perm(cur_item_set - {item}, cur_str + item):
                yield item2

g = gen_perm(set('abcd'))
print (list(g))
</code>```

Body:
guys.
It seems like I don't really understand the concept of Python generator functions, because I haven't figured out mistake in this code that is supposed to produce all the permutations of the string characters.

For instance, this one is based on simple set expansion and it works

def permutations(seq):
    perm_set = set()

    def perm(cur_item_set, cur_str=''):
        if not cur_item_set:
            perm_set.add(cur_str)
        else:
            for item in cur_item_set:
                perm(cur_item_set - set(item), cur_str + item)

    perm(set(seq))

    for (i, item) in enumerate(perm_set):
        print(i + 1, item)

    permutations('abcdef')

Meanwhile, this code doesn't work: list(g) provides []

def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            gen_perm(cur_item_set - {item}, cur_str + item)

g = gen_perm(set('abcd'))

Body:
When you recursively call gen_perm(), you don't do anything with the return value.

Try this, if yield from is available in your Python version (3.3 and above):

def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            yield from gen_perm(cur_item_set - {item}, cur_str + item)

g = gen_perm(set('abcd'))
print (list(g))

Or this will work on all Python versions.

def gen_perm(cur_item_set, cur_str=''):
    if not cur_item_set:
        yield cur_str
    else:
        for item in cur_item_set:
            for item2 in gen_perm(cur_item_set - {item}, cur_str + item):
                yield item2

g = gen_perm(set('abcd'))
print (list(g))


问:
Dotnet Core 1.1 MVC Javascript placed inside @section Scripts{ } is not rendered
I am writing a web application that uses dotnet core 1.1 MVC. I could not figure out why a javascript placed inside @section is not rendered??

I verified my _Layout.cshtml to contain

```<code>@RenderSection("Scripts", required: false)
</body>
</code>```

Here is how my views are laid out. For brevity, i have consolidated the code.

(does not work)

Create.cshtml:

```<code><h2>Create</h2>
@{Html.RenderPartial("_CreateOrEdit", Model);}

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
</code>```

_CreateOrEdit.cshtml

```<code><div class="row">
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts
{
<script type="text/javascript">
        $(document).ready(function () {
            $('.datepicker').datepicker({
                format: "dd.mm.yyyy",
                todayBtn: "linked",
                language: "de"
            });
        });
</script>
}
</code>```

The challenge i am facing is. the above Scripts section, present in _CreateOrEdit.cshtml is not rendered.

However if i placed this script inside the Scripts section in Create.cshtml as shown below, it is rendered.. what am i doing wrong.?

(works)

Create.cshtml

```<code><h2>Create</h2>
@{Html.RenderPartial("_CreateOrEdit", Model);}

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

<script type="text/javascript">
        $(document).ready(function () {
            $('.datepicker').datepicker({
                format: "dd.mm.yyyy",
                todayBtn: "linked",
                language: "de"
            });
        });
</script>
}
</code>```

_CreateOrEdit.cshtml

```<code><div class="row">
    <a asp-action="Index">Back to List</a>
</div>
</code>```

答:
You can use @Scripts.Render("~/Scripts/myScript.js") for .js files and @Styles.Render("~/Content/myStylesheet.css") for css files when inside a partial view.

However, it's worth mentioning that if your scripts depend on other included scripts such as jquery then you may run into issues with this since you aren't necessarily guaranteed what order the scripts will load in.

It is recommended to include scripts on the parent page (or _layout if it will be needed site wide) as opposed to in a partial view

Body:
I am writing a web application that uses dotnet core 1.1 MVC. I could not figure out why a javascript placed inside @section is not rendered??

I verified my _Layout.cshtml to contain

@RenderSection("Scripts", required: false)

Here is how my views are laid out. For brevity, i have consolidated the code.

(does not work)

Create.cshtml:

Create

@{Html.RenderPartial("_CreateOrEdit", Model);}

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

_CreateOrEdit.cshtml

    Back to List

@section Scripts
{

}

The challenge i am facing is. the above Scripts section, present in _CreateOrEdit.cshtml is not rendered.

However if i placed this script inside the Scripts section in Create.cshtml as shown below, it is rendered.. what am i doing wrong.?

(works)

Create.cshtml

Create

@{Html.RenderPartial("_CreateOrEdit", Model);}

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}

_CreateOrEdit.cshtml

    Back to List


问:
Recommended JavaScript HTML template library for JQuery?
Any suggestions on which HTML template library would go well with JQuery?  Googling turns up quite a number of libraries but I'm not sure whether there is a well recognized library that would stand the test of time.</p>

答: There is a reasonable discussion document on this topic here, which covers a range of templating tools. Not specific to jQuery, though.</p>

OwnerDisplayName: Shiva

OwnerDisplayName: Marc Gravell


问:
WP7 Get visible items in listbox
I have a listbox in a WP7 application and I would like to retrieve a list of visible items in the listbox.  Actually, I am trying to retrieve the object that is visible so that when my application is tombstoned, I can resume it and write listbox.ScrollIntoView(lastVisibleItem);

If it matters, listbox is bound to a collection of custom objects with a datatemplate for customizing the way it looks.

Thanks in advance.

答:
It's possible to work out how far the list has been scrolled using the technique detailed in this answer.

You could then calculate which item(s) are displayed based on the size of the list and the height of the items displayed.

If different items can be diffferent sizes then this becomes more difficult as you need to consider the height of each individual item.

You also need to remember that only part of an item may be displayed.

Title: WP7 Get visible items in listbox


问:
Why is IdentityServer4 looking for 'Microsoft.IdentityModel.Tokens, Version=5.1.2.0, but references 5.1.3?
I am currently using the quick start to get a basic implementation going in my framework I'm building, and I'm busy adding in the following:

```<code> app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:5000",
    RequireHttpsMetadata = false,

    ApiName = "api1"
});
</code>```

I get the following error

```<code>Could not load file or assembly 'Microsoft.IdentityModel.Tokens,
Version=5.1.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

The problem is that I have installed the nuget packages as explained on the IdentityServer4 site:

```<code>IdentityServer4
IdentityServer4.AccessTokenValidation
</code>```

I've looked through the dependencies and 5.1.3 is installed along with these packages, but for some reason it is looking for 5.1.2.

I've cleared my nuget cache, restarted visual studio numerous times etc...

My code looks like this:

```<code> loggerFactory.Initialise(Configuration.GetSection("Logging"));

        _applicationProvider.ConfigurePreMvc(app, env, serviceProvider);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        })
        .UseSwagger();

        _applicationProvider.ConfigurePostMvc(app, env, serviceProvider);
</code>```

and where _applicationProvider.ConfigurePreMvc(app, env, serviceProvider); executes it is executing the following:

```<code>  var settings = serviceProvider.GetService<IOptions<Settings>>().Value;

        app
            .UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = settings.IdentityServerUrl,
                RequireHttpsMetadata = false,

                ApiName = "api1"
            });
</code>```

the error happens on .UseIdentityServerAuthentication

Any one else had this problem?
Strange how the version is wrong even though it specifies the dependency, I have also tried to download the package myself which is 5.1.4 and then it was suddenly looking for 5.1.3 and not 5.1.2, which is even more confusing...

答: If your project is just a Web API then you don't need IdentityServer4 package but just IdentityServer4.AccessTokenValidation. Try removing the other package and see if that helps. Check out the official docs!</p>

Body:
I am currently using the quick start to get a basic implementation going in my framework I'm building, and I'm busy adding in the following:

 app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:5000",
    RequireHttpsMetadata = false,

    ApiName = "api1"
});

I get the following error

Could not load file or assembly 'Microsoft.IdentityModel.Tokens,
Version=5.1.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

The problem is that I have installed the nuget packages as explained on the IdentityServer4 site:

IdentityServer4
IdentityServer4.AccessTokenValidation

I've looked through the dependencies and 5.1.3 is installed along with these packages, but for some reason it is looking for 5.1.2.

I've cleared my nuget cache, restarted visual studio numerous times etc...

My code looks like this:

 loggerFactory.Initialise(Configuration.GetSection("Logging"));

        _applicationProvider.ConfigurePreMvc(app, env, serviceProvider);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        })
        .UseSwagger();

        _applicationProvider.ConfigurePostMvc(app, env, serviceProvider);

and where _applicationProvider.ConfigurePreMvc(app, env, serviceProvider); executes it is executing the following:

  var settings = serviceProvider.GetService<IOptions<Settings>>().Value;

        app
            .UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = settings.IdentityServerUrl,
                RequireHttpsMetadata = false,

                ApiName = "api1"
            });

the error happens on .UseIdentityServerAuthentication

Any one else had this problem?
Strange how the version is wrong even though it specifies the dependency, I have also tried to download the package myself which is 5.1.4 and then it was suddenly looking for 5.1.3 and not 5.1.2, which is even more confusing...


问:
Error with a bash loop for sqlite insert
I'm trying to insert stuff in db whith a while loop, but after 2 inserts my loop break ...
here the code:

```<code>x=0
while [[ "$x" < 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')
done
</code>```

So I tried to do that  but unsuccess too.

```<code>y=0
x=0
while [[ "$y" < 5 ]];do
    while [[ "$x" < 10 ]];do
        ((x++))
        sqlite my_db.db "insert into (col) values ('$x...')"
    done
    ((y++))
done
</code>```

But once again its only insert 2 times ...
So why did i have this error and how to fixe that ? thx.

答:
Because your code never resets x to 0 (or anything less than 10). Additionally, you're using the wrong operator (which is why the first snippet isn't working).</p>

```<code>x=0
y=0
while [[ $y -lt 5 ]];do
   x=0
   while [[ $x -lt 10 ]];do
      ((x++))
      sqlite my_db.db "insert into (col) values ('$x...')
   done
   ((y++))
done
</code>```

Body:
I'm trying to insert stuff in db whith a while loop, but after 2 inserts my loop break ...
here the code:

x=0
while [[ "$x" < 10 ]];do
    ((x++))
    sqlite my_db.db "insert into (col) values ('$x...')
done

So I tried to do that  but unsuccess too.

y=0
x=0
while [[ "$y" < 5 ]];do
    while [[ "$x" < 10 ]];do
        ((x++))
        sqlite my_db.db "insert into (col) values ('$x...')"
    done
    ((y++))
done

But once again its only insert 2 times ...
So why did i have this error and how to fixe that ? thx.

Body:
Because your code never resets x to 0 (or anything less than 10). Additionally, you're using the wrong operator (which is why the first snippet isn't working).

x=0
y=0
while [[ $y -lt 5 ]];do
   x=0
   while [[ $x -lt 10 ]];do
      ((x++))
      sqlite my_db.db "insert into (col) values ('$x...')
   done
   ((y++))
done