AWS |
lambdaタグが付けられた新着投稿 - Qiita |
AWS Service Quotas経由でLambda関数の同時実行数の上限緩和申請を自動化してみた。 |
https://qiita.com/matsumikan/items/8759de70fd1f7c69f9e0
|
awsservicequotas |
2023-04-30 01:18:07 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
AWS Service Quotas経由でLambda関数の同時実行数の上限緩和申請を自動化してみた。 |
https://qiita.com/matsumikan/items/8759de70fd1f7c69f9e0
|
awsservicequotas |
2023-04-30 01:18:07 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
【初学者向け】Dockerでデータベースを操作してみよう!(MySQL) |
https://qiita.com/yuta_931214/items/b8124445aa56c5b711be
|
docker |
2023-04-30 01:08:03 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
【Kubernetes構築】alphineLinuxを用いたk8s構築(web/ap/dbサーバ) |
https://qiita.com/t_kyn/items/715982eb347c715078b9
|
alphinelinux |
2023-04-30 01:01:19 |
海外TECH |
MakeUseOf |
4 Ways to Fix the Mail App's "Can’t Get Mail" Error on Windows 11 |
https://www.makeuseof.com/mail-app-cant-get-mail-windows/
|
error |
2023-04-29 16:15:16 |
海外TECH |
MakeUseOf |
How to Turn On Optional and Experimental Quest 2 Control and Input Features |
https://www.makeuseof.com/how-to-turn-on-optional-and-experimental-quest-2-control-and-input-features/
|
features |
2023-04-29 16:01:17 |
海外TECH |
DEV Community |
Custom API Gateway Authorizer with Golang |
https://dev.to/aws-builders/custom-api-gateway-authorizer-with-golang-3l25
|
Custom API Gateway Authorizer with GolangOne of the nice things about building with Serverless is that you can design things in a way that the pieces are composeable This means that you can put logic cohesively with other like minded logic and then keep things loosely coupled from other components so that things are easy to change without being too fragile When building an API you often need an Authorizer of sorts to validate the token that is being supplied In this article I m going to walk through building a custom API Gateway Authorizer with Golang API Gateway Authorizer with GolangFor reference here is the architecture diagram for what I want to show you What the above achieves is the following Defines an API Gateway for managing payloads to our resources Uses a Lamabda to handle Authorization Validates the token against a Cognito User Pool Leverages a cache with a custom set TTL to save compute Finally if all is good allows access to the Protected Resource will also be able to supply overrides into the Claim ContextThere is a companion half to this article as well that I ll show you how to extend the JWT that we ll be working with by using Lambdas and DyanamoDB If you are curious about that here s the article to show you how that s done Walking through the Code CDK Start with CognitoTo have a Cognito to validate against we first need to build a Cognito instance as well as a Client to be able to log in Defining the UserPool looks like the below Not much that needs additional explaining so let s move on to the Client this pool new cognito UserPool this SamplePool userPoolName SamplePool selfSignUpEnabled false signInAliases email true username true preferredUsername true autoVerify email false standardAttributes email required true mutable true customAttributes isAdmin new cognito StringAttribute mutable true passwordPolicy minLength requireLowercase true requireDigits true requireUppercase true requireSymbols true accountRecovery cognito AccountRecovery EMAIL ONLY removalPolicy cdk RemovalPolicy DESTROY Adding a Client to a UserPool is also straightforward So many options but mine below is pretty vanilla With this client you can then have a way to login in with the user and do other app development against it As you ll see later on in the article I m just using Postman to pull all this together this pool addClient sample client userPoolClientName sample client authFlows adminUserPassword true custom true userPassword true userSrp false idTokenValidity Duration minutes refreshTokenValidity Duration days accessTokenValidity Duration minutes Build the AuthorizerNow for the custom in building a custom API Gateway Authorizer with Golang The Authorizer is nothing more than a Lambda function So this could be an import from another stack if you desire But for simplicity I ve included everything in this one set of infrastructure If you want to take a deeper dive into CDK and GoFunction here s an article that helps you out Function definition in CDK export class AuthorizerFunction extends Construct private readonly func GoFunction constructor scope Construct id string poolId string super scope id this func new GoFunction this AuthorizerFunc entry path join dirname src authorizer functionName authorizer func timeout Duration seconds environment USER POOL ID poolId get function GoFunction return this func As I mentioned above a simple GoFunction implementation The only interesting thing to note is the environment variable for the USER POOL ID Let s take a look at why that matters Function implementation in GolangFor this example of building a custom API Gateway Authorizer with Golang I m going to validate the JWT and add some additional context Your implementation could be much different which again is why I like this approach You could have several different authorizers based on need and your Protected Resources do not know about what s happening above them in the call stack The first thing I want to show you is how to establish the keyset for the well known Cognito endpoint I m doing this in the init function because I know it ll run once when the Lambda initializes and then I m caching the output in a variable that ll maintain itself across Lambda invocations Not cold starts but invocations func init log SetFormatter amp log JSONFormatter PrettyPrint false log SetLevel log DebugLevel region us west poolId os Getenv USER POOL ID var err error jwksUrl fmt Sprintf https cognito idp s amazonaws com s well known jwks json region poolId keySet err jwk Fetch context TODO jwksUrl if err nil log WithFields log Fields error err url jwksUrl Fatal error getting keyset The jwksUrl variable above is documented in the AWS Developer guide And I m using the github com lestrrat go jwx jwt to represent the KeySet that I ll be working with to validate the authenticity and the expiration of the token Remember the USER POOL ID variable in the CDK above This is where it comes into play Building that well known endpoint requires the UserPoolIdThe next part of this process is to perform the validation I m not going to go into the specifics in this article of how this happens but essentially the library is going to Verify the structure of the token Verify the signing key matches the algorithm the key used Verify the expiration and that the token hasn t expiredThat s the nice thing about using a library And here s how to invoke it bounds len event AuthorizationToken token event AuthorizationToken bounds parsedToken err jwt Parse byte token jwt WithKeySet keySet jwt WithValidate true The output of the jwt Parse will return an error if any of the above fails This means in that case you can issue a denial Like this return events APIGatewayCustomAuthorizerResponse PrincipalID PolicyDocument events APIGatewayCustomAuthorizerPolicy Version Statement events IAMPolicyStatement Action string execute api Invoke Effect Deny Here is the rejection Resource string UsageIdentifierKey nilNotice I m not returning an error This is simply going to deny access A response is not an error so why return one And in the case of everything being solid just return the allow return events APIGatewayCustomAuthorizerResponse PrincipalID PolicyDocument events APIGatewayCustomAuthorizerPolicy Version Statement events IAMPolicyStatement Action string execute api Invoke Effect Allow Return Allow Resource string Context DumpClaims parsedToken UsageIdentifierKey nilI also want to highlight that DumpClaims function What does that do One of the cool things about Lambda Authorizers is that you can extend what gets sent along as context to downstream parties What if you wanted to carry parts of the token down to the intended destination The request will send along the details that are public to the JWT but private claims or things you extended aren t going to be passed along Maybe a customerId Maybe some roles func DumpClaims token jwt Token map string interface m make map string interface m customKey SomeValueHere return m For this article it s simple I m just adding a customKey into the context I ll show you how that shows up shortly CDK The Protected ResourceHalf the fun of building a custom API Gateway Authorizer with Golang is over That just means the other half is about to start What do we do now that we ve got an authorizer in place Put a Protected Resource behind it of course constructor scope Construct id string func IFunction super scope id const authorizer new TokenAuthorizer this TokenAuthorizer authorizerName BearTokenAuthorizer handler func this api new RestApi this RestApi description Sample API restApiName Sample API deployOptions stageName main defaultMethodOptions authorizer authorizer That is the API Gateway CDK code Notice in the defaultMethodOptions that I m adding an authorizer It s just a IFunction Which again could be an import or in our case it s the Authorizer we just built Now with an API we can create a Resource constructor scope Construct id string api RestApi super scope id this func new GoFunction this ProtectedResource entry path join dirname src protected resource functionName protected resource func timeout Duration seconds api root addMethod GET new LambdaIntegration this func proxy true For our example I m using a Lambda Proxy Integration and defining it at the root level So we can expect a GET request on the path The actual handler for this endpoint is again a simple demonstration func handler ctx context Context event events APIGatewayProxyRequest events APIGatewayProxyResponse error success amp Response Message Congrats A Payload CustomKey event RequestContext Authorizer customKey string b json Marshal success return amp events APIGatewayProxyResponse Body string b StatusCode Headers map string string Content Type application json nil Notice the use of the customKey and the event RequestContext Authorizer customKey string This event RequestContext Authorizer holds a map string interface that you can use to your advantage Use cases are endless but I use it a lot for customer details and user roles and profile data that I ve extended Putting it All TogetherLet s put together the output of a custom API Gateway Authorizer with Golang For that here s the scenario for testing this all together First ThingIn a bootstrapped account basecdk deploy Create a Cognito UserOnce the infrastructure is deployed you should have Lambdas Authorizer ProtectedResource API Gateway One endpoint to the ProtectedResource with the Authoirzer attached An Authorizer A Deployed Stage A Cognito UserPoolHere is what your UserPool should look like Notice the User Pool ID I ve cleared mine for reasons You ll want to copy that ID as it ll matter later Now the Client ListThe ClientID in that table will be important too Again mine s cleared out but take note of yours Last create a user and mark them as verified Mark down their password as we are going to use the Password Flow to login in a minute Tour the API GatewayFor our main Protected Resource this is how it gets createdThe Authorization field points at the BearerTokenAuthorizer we defined way up at the beginning of this article And then that Authorizer is defined on the API Gateway as such Keep in mind if you use Base Path Mapping as defined in this article and are sharing the Authorizer you ll need to attach it for each of your API Gateways Executing the RequestWe are finally ready to run this thing But first let s snag a token Remember I said to capture the ClientID in the UserPool Now s the time to bring that out The output of this is going to be your three tokens Access Token ID Token Refresh TokenFeel free to use either the ID or the Access in the next request Making the request is simple Failure RequestFirst let s see what happens with a Bad TokenPostman requestAnd your Logs in CloudWatch should look like this Successful RequestNow for success Postman requestAnd your Logs in CloudWatch should look like thisYou ve done it Testing this Locally with Sample EventsI d be remiss if I didn t include that you can also do some local testing of the authorizer This can happen in ways Some Unit tests Using a test event file Running the Local FileIf you execute cdk synth locally on this stack you ll end up with a MainStack template json in the cdk out directory You can run the test file included in the repos like thisbashsam local invoke AuthorizerFunc t cdk out MainStack template json event src authorizer test events e json env vars environment json skip pull image Wrapping UpThat was a long article with a lot of details but this pattern is so helpful when building secure and scalable APIs with Serverless technologies By adding a custom API Gateway Authorizer with Golang you can capture this authorization logic high up the stack this saving downstream resources from having to deal with this repetitive code In addition but leveraging the context of the event to your downstream Lambda you can make use of the PrivateClaims that you might have customized If you want to see all of this for yourself so you can run it locally visit my GitHub repositoryAs always thanks for reading and hope this helps you build some more cool Serverless Apps |
2023-04-29 16:01:46 |
Apple |
AppleInsider - Frontpage News |
Showrunner 'hate' causing delays in making 'Severance' season 2 |
https://appleinsider.com/articles/23/04/29/showrunner-hate-causing-delays-in-making-severance-season-2?utm_medium=rss
|
Showrunner x hate x causing delays in making x Severance x season The second season of the critically acclaimed Apple TV original Severance is becoming a headache with delays caused by the showrunners hating each other Image credit Apple The first season of the Ben Stiller directed near future thriller Severance received numerous nominations and was very well received by viewers and critics alike While filming for the second season started in October it seems that the show may return to Apple TV later than originally intended due to some production problems Read more |
2023-04-29 16:35:21 |
海外TECH |
Engadget |
Leaked Google Pixel Fold images show a sleek, nearly gapless hinge |
https://www.engadget.com/leaked-google-pixel-fold-images-show-a-sleek-nearly-gapless-hinge-160537647.html?src=rss
|
Leaked Google Pixel Fold images show a sleek nearly gapless hingeWith Google I O less than two weeks away the Pixel leaks are starting to come hard and fast On Friday leaker and former Engadget editor Evan Blass shared via The Verge two K renders of the Pixel Fold The images almost certainly originally came from Google so they offer our best look at the device yet Unfortunately Blass didn t post an image of the front of the foldable so for at least the time being we can t compare the renders against the alleged video of the Pixel Fold that leaker Kuba Wojciechowski uploaded on April st What s more the one render of the Fold s back cover doesn t give a sense of how pronounced the camera bump is However they do show a device that looks sleeker than the one we ve seen leak before Evan BlassThe Pixel Fold will reportedly cost when it arrives later this year According to a recent CNBC report the device will feature a inch foldable display and a inch external screen It will also supposedly sport the “most durable hinge on any foldable device to date Judging from the images Blass shared there may be some merit to that claim nbsp Separately Blass shared an image of the Pixel a in a striking coral colorway Google is expected to offer its next midrange device in three other colors ーblue black and white ーand the device could cost more than its predecessor With Google I O set for May th expect to learn more about the Pixel Fold and Pixel a soon nbsp nbsp This article originally appeared on Engadget at |
2023-04-29 16:05:37 |
ニュース |
BBC News - Home |
Gunman kills five, including child, at Texas home |
https://www.bbc.co.uk/news/world-us-canada-65437185?at_medium=RSS&at_campaign=KARANGA
|
mexican |
2023-04-29 16:33:39 |
ニュース |
BBC News - Home |
Sudan crisis: NHS doctors told they can catch last UK evacuation flights |
https://www.bbc.co.uk/news/uk-65433363?at_medium=RSS&at_campaign=KARANGA
|
british |
2023-04-29 16:27:32 |
ニュース |
BBC News - Home |
World Snooker Championship 2023 results: Luca Brecel into final after stunning comeback win over Si Jiahui |
https://www.bbc.co.uk/sport/snooker/65437757?at_medium=RSS&at_campaign=KARANGA
|
World Snooker Championship results Luca Brecel into final after stunning comeback win over Si JiahuiLuca Brecel wins frames in a row during the greatest ever Crucible comeback to beat Si Jiahui and reach the World Championship final |
2023-04-29 16:54:11 |
ニュース |
BBC News - Home |
Brentford 2-1 Nottingham Forest: Ivan Toney and Josh Dasilva cancel out Danilo opener |
https://www.bbc.co.uk/sport/football/65357222?at_medium=RSS&at_campaign=KARANGA
|
Brentford Nottingham Forest Ivan Toney and Josh Dasilva cancel out Danilo openerNottingham Forest are stunned as a late Brentford fightback denies them precious points in their fight for Premier League survival |
2023-04-29 16:42:53 |
コメント
コメントを投稿